Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'List of lists' to 'list' without losing empty lists from the original list of lists

Usually I would use a comprehension to change my list of lists to a list. However, I don't want to lose the empty lists as I will zip the final list to another list and I need to maintain the placings.

I have something like

list_of_lists = [['a'],['b'],[],['c'],[],[],['d']] and I use this

[x for sublist in list_of_lists for x in sublist] which gives me

['a','b','c','d'] but what I would like is

['a','b','','c','','','d']

Sorry if this is a stupid question, I am new to python.

Thanks for any help!

like image 464
user1792403 Avatar asked Aug 02 '13 16:08

user1792403


2 Answers

Are you starting with the strings 'a', 'b', etc.? If so then you can use ''.join to convert ['a'] into 'a' and [] into ''.

[''.join(l) for l in list_of_lists]
like image 181
John Kugelman Avatar answered Nov 02 '22 23:11

John Kugelman


Simply choose [''] instead of the empty list when presented with an empty sublist:

list_of_lists = [['a'],['b'], [], ['c'], [], [], ['d']]
[x for sublist in list_of_lists for x in sublist or ['']]

If you have some more complicated criteria for treating some sublists specially, you can use ... if ... else ...:

[x for sublist in list_of_lists for x in (sublist if len(sublist)%2==1 else [42])]

P.s. I'm assumig that the lack of quotes in the original is an oversight.

like image 30
Robᵩ Avatar answered Nov 02 '22 22:11

Robᵩ