Tarun K Tarun K - 3 months ago 7
Python Question

How to group list with index wise?

I have a list of list where i need to group elements by using user input ( see

split
variable in code ) and create new list.
I have tried but instead of grouping, elements are concatenated separately

split = 3 # user input
data = [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14], [15,16], [17,18]]
z = [] ; y = []
for i,d in enumerate(data):
z.append(d)
if (i+1)%split==0:
y.append(z)
z = []
xx = (y+[z])
print(xx)
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]], []]
# ^____________________^ ^_______________________^ this needs to be merged


input :

data = [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14], [15,16], [17,18]]


expected output :

[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]

Answer

Here is one way using list comprehension:

>>> sp = 3
>>> fragment = len(data)//sp
>>> [[t for item in data[i:i+fragment] for t in item] for i in range(0, len(data), fragment)]
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]

And here is an intertools based recipe:

>>> from itertools import islice, chain
>>> 
>>> [list(chain.from_iterable(islice(data, i, i+fragment))) for i in range(0, len(data), fragment)]
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]