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!
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]
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.
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