python实现列表的等分

来源:互联网 发布:大数据时代变革 编辑:程序博客网 时间:2024/05/01 16:17

转自https://my.oschina.net/u/1431297/blog/618995

这里主要借助itertools模块里的izip和iziplongest方法,代码如下

from itertools import zip_longest    # zip_longest -> Python 3, izip_longest -> Python 2chunk_list = lambda a_list, n: zip_longest(*[iter(a_list)]*n)result_groups = list(chunk_list([x for x in range(100)], 8))Out[12]: [(0, 1, 2, 3, 4, 5, 6, 7), (8, 9, 10, 11, 12, 13, 14, 15), (16, 17, 18, 19, 20, 21, 22, 23), (24, 25, 26, 27, 28, 29, 30, 31), (32, 33, 34, 35, 36, 37, 38, 39), (40, 41, 42, 43, 44, 45, 46, 47), (48, 49, 50, 51, 52, 53, 54, 55), (56, 57, 58, 59, 60, 61, 62, 63), (64, 65, 66, 67, 68, 69, 70, 71), (72, 73, 74, 75, 76, 77, 78, 79), (80, 81, 82, 83, 84, 85, 86, 87), (88, 89, 90, 91, 92, 93, 94, 95), (96, 97, 98, 99, None, None, None, None)]

这里借助了迭代器,关于

*[iter(a_list)]*n
参考了stackoverflow里的精彩说明,如下

iter() is an iterator over a sequence. [x] * n produces a list containing n quantity of x, i.e. a list of length n, where each element is x*arg unpacks a sequence into arguments for a function call. Therefore you're passing the same iterator 3 times to zip(), and it pulls an item from the iterator each time.

x = iter([1,2,3,4,5,6,7,8,9])print zip(x, x, x)
最终产生了一个等分list的方法。

等分list可以用来批量处理数据,如等分目录下的文件等。

0 0
原创粉丝点击