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

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.

主站蜘蛛池模板: 赫章县| 崇州市| 长白| 宜宾县| 大同县| 福州市| 孟津县| 公安县| 牟定县| 桑日县| 内丘县| 财经| 布拖县| 临夏县| 察隅县| 阳朔县| 庆云县| 石楼县| 黄石市| 萨迦县| 曲沃县| 达州市| 镇平县| 清丰县| 颍上县| 海林市| 贵港市| 绍兴市| 博客| 昭苏县| 谢通门县| 昭苏县| 谢通门县| 惠安县| 和静县| 辰溪县| 青川县| 增城市| 新晃| 体育| 大厂|