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

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.

主站蜘蛛池模板: 印江| 山西省| 青龙| 尼玛县| 阳春市| 肃宁县| 焦作市| 比如县| 普洱| 临洮县| 新营市| 老河口市| 包头市| 中西区| 辽宁省| 孟津县| 昭觉县| 遂溪县| 新和县| 陇南市| 台东市| 加查县| 天津市| 芷江| 岳西县| 从化市| 泰安市| 鄢陵县| 宜宾市| 合水县| 拉萨市| 蓬溪县| 许昌县| 大理市| 乳山市| 聂荣县| 太谷县| 姚安县| 广灵县| 八宿县| 长治市|