- Functional Python Programming
- Steven F. Lott
- 393字
- 2021-08-27 19:20:29
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.
- 動手玩轉Scratch3.0編程:人工智能科創教育指南
- C/C++算法從菜鳥到達人
- 實戰低代碼
- Learning ELK Stack
- TypeScript項目開發實戰
- C語言程序設計實驗指導 (第2版)
- Learning Apache Cassandra
- Microsoft Windows Identity Foundation Cookbook
- Learning Dynamics NAV Patterns
- Scratch少兒編程高手的7個好習慣
- Learning Node.js for Mobile Application Development
- 亮劍C#項目開發案例導航
- Python自動化開發實戰
- jQuery權威指南
- Building an E-Commerce Application with MEAN