4

我有一个数字列表,如何将每个n数字分组为一个元组?

例如,如果我有一个列表a = range(10),并且我想将每 5 个项目分组为一个元组,那么:

b = [(0,1,2,3,4),(5,6,7,8,9)]

我怎样才能做到这一点?len(a)如果不是 的整数倍,我也想引发错误n

4

3 回答 3

10
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [tuple(a[i:i+5]) for i in range(0, len(a), 5)]
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
于 2013-03-07T08:46:31.207 回答
1
In [18]: def f(lst,n):    
    ...:     if len(lst)%n != 0:
    ...:         raise ValueError("{} is not a multiple of {}".format(len(lst),n))
    ...:     return zip(*[iter(lst)]*n)

In [19]: lst = range(10)

In [20]: f(lst,5)
Out[20]: [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]

In [21]: f(range(9),5)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-21-814a68e0035f> in <module>()
----> 1 f(range(9),5)

<ipython-input-18-3ca911a04fd3> in f(lst, n)
      1 def f(lst,n):
      2     if len(lst)%n != 0:
----> 3         raise ValueError("{} is not a multiple of {}".format(len(lst),n))
      4     return zip(*[iter(lst)]*n)

ValueError: 9 is not a multiple of 5
于 2013-03-07T08:58:45.387 回答
1

确定 N 是您的组长度

if (len(your_list)%n==0):
    wish_list = [ tuple(your_list[i:i+N]) for i in range(0, len(your_list), N) ]
else:
    raise Exception("not divisible by N")
于 2013-03-07T09:09:15.650 回答