I have a list of unequal lists. I would like to generate a new list with list comprehension from the sublists.
s = [['a','b','c','d'],['e','f','g'],['h','i'],['j','k','l','m']]
I am trying the following code but it keeps raising an indexError:
new_s = []
for i in range(len(s)):
new_s.append((i,[t[i] for t in s if t[i]))
The expected output would be:
new_s = [(0,['a','e','h','j']),(1,['b','f','i','k']),(2,['c','g','l']),(3,['d','m'])]
Any ideas how to get this to work?
You can use itertools.zip_longest
to iterate over each sublist elementwise, while using None
as the fill value for the shorter sublists.
Then use filter
to remove the None
values that were used from padding.
So all together in a list comprehension:
>>> from itertools import zip_longest
>>> [(i, list(filter(None, j))) for i, j in enumerate(zip_longest(*s))]
[(0, ['a', 'e', 'h', 'j']), (1, ['b', 'f', 'i', 'k']), (2, ['c', 'g', 'l']), (3, ['d', 'm'])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With