- Functional Python Programming
- Steven F. Lott
- 178字
- 2021-08-27 19:20:28
Unzipping a zipped sequence
We can insert zip() mapping can be inverted. We'll look at several ways to unzip a collection of tuples.
We can't fully unzip an iterable of tuples, since we might want to make multiple passes over the data. Depending on our needs, we may need to materialize the iterable to extract multiple values.
The first way is something we've seen many times: we can use a generator function to unzip a sequence of tuples. For example, assume that the following pairs are a sequence object with two-tuples:
p0= (x[0] for x in pairs) p1= (x[1] for x in pairs)
This will create two sequences. The p0 sequence has the first element of each two-tuple; the p1 sequence has the second element of each two-tuple.
Under some circumstances, we can use the multiple assignment of a for loop to decompose the tuples. The following is an example that computes the sum of the products:
sum(p0*p1 for for p0, p1 in pairs)
We used the for statement to decompose each two-tuple into p0 and p1.
推薦閱讀
- Advanced Machine Learning with Python
- Python 3.7網絡爬蟲快速入門
- OpenShift開發指南(原書第2版)
- 零基礎學Scratch少兒編程:小學課本中的Scratch創意編程
- JIRA 7 Administration Cookbook(Second Edition)
- 微服務設計原理與架構
- Mastering macOS Programming
- Visual Basic學習手冊
- GeoServer Beginner's Guide(Second Edition)
- 小學生C++創意編程(視頻教學版)
- Learning Unreal Engine Android Game Development
- Mastering ArcGIS Enterprise Administration
- Vue.js 2 Web Development Projects
- Learning Nessus for Penetration Testing
- R語言數據挖掘:實用項目解析