Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group list items into tuple? [duplicate]

I have a list of numbers, how can I group every n numbers into a tuple?

For example, if I have a list a = range(10) and I want to group every 5 items into a tuple, so:

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

How can I do this? I also want to raise an error if len(a) is not an integer multiple of n.

like image 272
LWZ Avatar asked Dec 16 '22 13:12

LWZ


2 Answers

>>> 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)]
like image 97
linbo Avatar answered Dec 21 '22 10:12

linbo


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
like image 29
root Avatar answered Dec 21 '22 10:12

root