官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 望奎县| 淄博市| 扬州市| 虹口区| 嘉禾县| 康定县| 东光县| 五原县| 建阳市| 建宁县| 扬中市| 衡阳县| 犍为县| 安乡县| 商城县| 南康市| 铜山县| 棋牌| 仪陇县| 黄浦区| 临潭县| 大足县| 寻乌县| 曲麻莱县| 毕节市| 房山区| 肃北| 潮安县| 武安市| 茂名市| 赤水市| 无极县| 于都县| 高州市| 噶尔县| 辽阳县| 咸宁市| 南郑县| 高碑店市| 沾化县| 蒲城县|