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

Structuring flat sequences – an alternative approach

Let's say we have a simple, flat list and we want to create pairs from this list.
The following is the required data:

flat= ['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', 
'31', '37', '41', '43', '47', '53', '59', '61', '67', '71',... ]

We can create pairs using list slices, as follows:

zip(flat[0::2], flat[1::2])

The slice flat[0::2] is all of the even positions. The slice flat[1::2] is all of the odd positions. If we zip these together, we get a two-tuple. The item at index  [0] is the value from the first even position, and then the item at index [1] is the value from the first odd position. If the number of elements is even, this will produce pairs nicely. If the total number of items is odd, the item will be dropped; there's a handy solution to this.

This expression has the advantage of being quite short. The functions shown in the previous section are longer ways to solve the same problem.

This approach can be generalized. We can use the *(args) approach to generate a sequence-of-sequences that must be zipped together. It looks like the following:

zip(*(flat[i::n] for i in range(n)))

This will generate n slices—flat[0::n], flat[1::n], flat[2::n], and so on, and flat[n-1::n]. This collection of slices becomes the arguments to zip(), which then interleaves values from each slice.

Recall that zip() truncates the sequence at the shortest list. This means that if the list is not an even multiple of the grouping factor n, (len(flat)%n != 0), which is the final slice, it won't be the same length as the others, and the others will all be truncated. This is rarely what we want.

If we use the itertools.zip_longest() method, then we'll see that the final tuple will be padded with enough None values to make it have a length of n. In some cases, this padding is acceptable. In other cases, the extra values are undesirable.

The list slicing approach to grouping data is another way to approach the problem of structuring a flat sequence of data into blocks. As it is a general solution, it doesn't seem to offer too many advantages over the functions in the previous section. As a solution specialized for making two-tuples from a flat last, it's elegantly simple.

主站蜘蛛池模板: 红原县| 沙坪坝区| 济源市| 那曲县| 宁强县| 绥阳县| 辽阳县| 五家渠市| 台中县| 大关县| 奉新县| 卢龙县| 景洪市| 溧阳市| 东源县| 孙吴县| 高陵县| 宜城市| 龙陵县| 包头市| 灵山县| 五寨县| 靖西县| 阿合奇县| 农安县| 广德县| 全南县| 上犹县| 雅江县| 广水市| 凤翔县| 灵川县| 固始县| 洛浦县| 湟源县| 黄大仙区| 伊春市| 黔西| 玉龙| 荆门市| 无为县|