How to make a list comprehension in python with unequal sublists

I have a list of unequal lists. I would like to create a new list with an understanding of the list of subscriptions.

s = [['a','b','c','d'],['e','f','g'],['h','i'],['j','k','l','m']] 

I try to use the following code, it keeps raising indexError

 new_s = [] for i in range(len(s)): new_s.append((i,[t[i] for t in s if t[i])) 

Expected Result:

 new_s = [(0,['a','e','h','j']),(1,['b','f','i','k']),(2,['c','g','l']),(3,['d','m'])] 

Any ideas how to make this work?

+7
python
source share
3 answers

You can use itertools.zip_longest to itertools.zip_longest over each sublist in half, using None as the fill value for shorter subscriptions.

Then use filter to remove the None values ​​that were used when filling.

So, all together in understanding the list:

 >>> 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'])] 
+11
source share

one without itertools, but changing the original list.

 def until_depleted(): while any(sl for sl in s): yield 1 list(enumerate(list(s_l.pop(0) for s_l in s if s_l) for _ in until_depleted())) 

without changing the original, but using the counter

 idx = 0 max_idx = max(len(_) for _ in s) def until_maxidx(): global idx while idx < max_idx: yield 1 idx += 1 list(enumerate(list(s_l[idx] for s_l in s if idx < len(s_l)) for _ in until_maxidx())) 

More explicit without internal understanding and calling generators:

 ret = [] idx = 0 max_idx = max(len(_) for _ in s) while idx < max_idx: ret.append(list(s_l[idx] for s_l in s if idx < len(s_l))) idx += 1 print(list(enumerate(ret))) 
0
source share

This is without itertools, but also without understanding, so I don’t know if this is considered a solution.

 s = [['a','b','c','d'],['e','f','g'],['h','i'],'j','k','l','m']] new_s = [] for i in range(len(s)): tmp = [] for item in s: tmp.extend(item[i:i+1]) new_s.append((i, tmp)) 
0
source share

All Articles