Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list comprehension in python with unequal sublists

Tags:

python

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?

like image 209
Jadox Avatar asked Mar 08 '18 15:03

Jadox


1 Answers

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'])]
like image 154
Cory Kramer Avatar answered Sep 24 '22 05:09

Cory Kramer