'To get new list

I have a list of lists:

s= [[1, 2, 3],
[56, 88, 78],
[100, 500, 999],
[22, 88, 99],
[111, 555, 777],
[71, 91, 31]]

and I have to get a new list:

s1 = ([ 1, 2, 3, 56, 88, 78, 100, 500, 999], [ 22, 88, 99, 111, 555, 777, 71, 91, 31]) 

I try to do next:

s1=[]
for i in range(len(s)-3):
    s1.append(np.concatenate(s[i:i+3])) 
    i+=3

Of course, I got another list than I need. What should I do to get a right list?



Solution 1:[1]

If you want to iterate on the indices of the sublist 3 by 3, you can use range with a step of 3.

In order to concatenate the 3 sublists, you can take advantage of itertools.chain.from_iterable that will yield the items of the sublists one after the other.

from itertools import chain

s= [[1, 2, 3],
[56, 88, 78],
[100, 500, 999],
[22, 88, 99],
[111, 555, 777],
[71, 91, 31]]

out = [list(chain.from_iterable(s[i:i+3])) for i in range(0, len(s), 3)]

print(out)
# [[1, 2, 3, 56, 88, 78, 100, 500, 999], [56, 88, 78, 100, 500, 999, 22, 88, 99]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thierry Lathuille