如何将列表中的元素分组到元组列表?

时间:2013-01-28 17:45:02

标签: python tuples

  

可能重复:
  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,)]

感谢。

1 个答案:

答案 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)(转换为元组除外) )。

相关问题