Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change nested list into multiple single lists

If I have a list:

[[ A, B, C ], 10, [ 1, 2, 3 ], F]

What would be the best way to change it into:

[ A, 10, 1, F]
[ B, 10, 2, F]
[ C, 10, 3, F]

The length of the nested lists are consistent: len(list[0]) == len(list[2]), but len(list[0]) might be 3, 2, 4, etc.

like image 531
Andrew Avatar asked Oct 27 '25 07:10

Andrew


1 Answers

Let's try itertools here:

from itertools import cycle

list(zip(*(iter(x) if isinstance(x, list) else cycle([x]) for x in l)))
# [('A', 10, 1, 'F'), ('B', 10, 2, 'F'), ('C', 10, 3, 'F')]

Note that this will not error out if the sub-lists are unequally sized - the size of the output is equal to the size of the shortest sub-list.


How It Works

Iterate over the list, if the item is a list then convert it into an iterator with iter, otherwise if scalar convert it into a circular iterator (infinitely repeating single value) and zip them together and listify.

Step 0

 A     10    1      F
 B           2   
 C           3
l[0]  l[1]  l[2]  l[3]

Step 1

(iter(x) if isinstance(x, list) else cycle([x]) for x in l)

 A     10    1      F
 B     10    2      F
 C     10    3      F
l[0]  l[1]  l[2]  l[3]

Step 2

list(zip(*_))
[('A', 10, 1, 'F'), ('B', 10, 2, 'F'), ('C', 10, 3, 'F')]
like image 91
cs95 Avatar answered Oct 28 '25 19:10

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!