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

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.

主站蜘蛛池模板: 新竹县| 颍上县| 宜州市| 昌宁县| 青龙| 绥中县| 凤城市| 藁城市| 陕西省| 富顺县| 广州市| 沅陵县| 绥江县| 绥德县| 泰和县| 长海县| 措勤县| 大渡口区| 大埔县| 杭锦旗| 禄丰县| 阿拉尔市| 渝北区| 庄河市| 海阳市| 富平县| 襄城县| 深泽县| 马鞍山市| 三都| 儋州市| 信阳市| 贺兰县| 梨树县| 广德县| 周口市| 二手房| 龙海市| 义马市| 当阳市| 桂东县|