可能重复:
What is the most “pythonic” way to iterate over a list in chunks?
以下是我的问题示例:
l = [1,2,3,4,5,6,7,8,9]
然后,如果groupsize = 3,我想:
l1 = [(1,2,3),(4,5,6),(7,8,9)]
如果groupsize = 4,则
l1 = [(1,2,3,4),(5,6,7,8),(9,)]
感谢。
答案 0 :(得分:2)
In [1]: def group(l, size):
...: return [tuple(l[i:i+size]) for i in range(0, len(l), size)]
...:
In [2]: l = [1,2,3,4,5,6,7,8,9]
In [3]: group(l, 3)
Out[3]: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
In [4]: group(l, 4)
Out[4]: [(1, 2, 3, 4), (5, 6, 7, 8), (9,)]
如果您决定需要生成器,则可以将[]
更改为()
并获得等效的this answer(以及this one)(转换为元组除外) )。