我有以下问题。我有一个列表:
>>> l = list(range(20))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> # What I want:
>>> [[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9] , ...]
如何以最pythonic的方式将我的列表放入长度为4的k个片段中?我觉得我想念一些明显的东西。我完全了解How do you split a list into evenly sized chunks?,但仍然没有线索......
提前致谢!
答案 0 :(得分:2)
您已发布链接的问题答案的直接副本。唯一的变化是xrange
中的步骤 - 从n
到n - 1
:
def chunks(l, n):
for i in xrange(0, len(l), n - 1):
yield l[i:i + n]
list(chunks(range(20), 4))
[[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9], [9, 10, 11, 12], [12, 13, 14, 15], [15, 16, 17, 18], [18, 19]]
答案 1 :(得分:0)
zip(*[iter(list(range(20)))]*4)
答案 2 :(得分:0)
a = range(20)
b = [a[i:i+4] for i in xrange(0, len(a), 4)]
print b
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]