如果你想将列表分成多个部分,你可以使用这个技巧:
list_of_slices = zip(*(iter(the_list),) * slice_size)
例如
>>> zip(*(iter(range(10)),) * 3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
如果项目数量不能除以切片大小,并且您想用 None 填充列表,您可以执行以下操作:
>>> map(None, *(iter(range(10)),) * 3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
这是一个肮脏的小伎俩
好的,我将解释它是如何工作的。解释起来会很棘手,但我会尽力。
首先是一些背景:
在 Python 中,您可以将列表乘以一个数字,如下所示:
[1, 2, 3] * 3 -> [1, 2, 3, 1, 2, 3, 1, 2, 3]
([1, 2, 3],) * 3 -> ([1, 2, 3], [1, 2, 3], [1, 2, 3])
And an iterator http://docs.python.org/library/functions.html?highlight=iter#iter对象可以像这样被消耗一次:
>>> l=iter([1, 2, 3])
>>> l.next()
1
>>> l.next()
2
>>> l.next()
3
The zip http://docs.python.org/library/functions.html#zip函数返回一个元组列表,其中第 i 个元组包含每个参数序列或可迭代对象中的第 i 个元素。例如:
zip([1, 2, 3], [20, 30, 40]) -> [(1, 20), (2, 30), (3, 40)]
zip(*[(1, 20), (2, 30), (3, 40)]) -> [[1, 2, 3], [20, 30, 40]]
zip 前面的 * 用于解压参数。您可以找到更多详细信息here http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists.
So
zip(*[(1, 20), (2, 30), (3, 40)])
实际上相当于
zip((1, 20), (2, 30), (3, 40))
但适用于可变数量的参数
现在回到技巧:
list_of_slices = zip(*(iter(the_list),) * slice_size)
iter(the_list)
-> 将列表转换为迭代器
(iter(the_list),) * N
-> 将生成对 the_list 迭代器的 N 引用。
zip(*(iter(the_list),) * N)
-> 将把这些迭代器列表送入 zip 中。这又会将它们分组为 N 大小的元组。但由于所有 N 个项目实际上都是对同一个迭代器的引用iter(the_list)
结果将被重复调用next()
在原始迭代器上
我希望这能解释它。我建议您采用更容易理解的解决方案。我只是想提及这个技巧,因为我喜欢它。