- 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.
推薦閱讀
- C#高級編程(第10版) C# 6 & .NET Core 1.0 (.NET開發經典名著)
- C語言程序設計(第3版)
- Windows Forensics Cookbook
- Unity 5.x By Example
- 小學生C++創意編程(視頻教學版)
- 用戶體驗增長:數字化·智能化·綠色化
- 前端HTML+CSS修煉之道(視頻同步+直播)
- C語言程序設計
- Python Data Science Cookbook
- 從零開始:UI圖標設計與制作(第3版)
- OpenCV 3計算機視覺:Python語言實現(原書第2版)
- Mockito Essentials
- 遠方:兩位持續創業者的點滴思考
- Python預測分析實戰
- Learning Cocos2d-JS Game Development