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

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.

主站蜘蛛池模板: 垫江县| 德化县| 库车县| 吉隆县| 偃师市| 安义县| 海淀区| 泸州市| 高邮市| 循化| 湾仔区| 万山特区| 驻马店市| 高州市| 沙河市| 日喀则市| 乐昌市| 大城县| 理塘县| 金堂县| 元朗区| 武邑县| 白山市| 长子县| 珲春市| 黄大仙区| SHOW| 垣曲县| 大悟县| 蓬溪县| 宿迁市| 吉林省| 萍乡市| 延寿县| 吴江市| 石台县| 利辛县| 乌海市| 景泰县| 楚雄市| 新昌县|