通常我会使用理解来将列表列表更改为列表。但是,我不想丢失空列表,因为我将最终列表压缩到另一个列表,我需要维护这些位置。
我有类似
的东西 list_of_lists = [['a'],['b'],[],['c'],[],[],['d']]
我用这个
[x for sublist in list_of_lists for x in sublist]
这给了我
['a','b','c','d']
但我想要的是
['a','b','','c','','','d']
很抱歉,如果这是一个愚蠢的问题,我是python的新手。
感谢您的帮助!
答案 0 :(得分:5)
您是从字符串'a'
,'b'
等开始的吗?如果是,那么您可以使用''.join
将['a']
转换为'a'
,将[]
转换为''
。
[''.join(l) for l in list_of_lists]
答案 1 :(得分:5)
当出现空子列表时,只需选择['']
而不是空列表:
list_of_lists = [['a'],['b'], [], ['c'], [], [], ['d']]
[x for sublist in list_of_lists for x in sublist or ['']]
如果您有一些更复杂的标准来专门处理某些子列表,您可以使用... if ... else ...
:
[x for sublist in list_of_lists for x in (sublist if len(sublist)%2==1 else [42])]
P.S。我觉得原版中缺少引号是一种疏忽。
答案 2 :(得分:1)
类似的东西:
a = b = c = d = 3
lol = [[a],[b],[],[c],[],[],[d]]
from itertools import chain
print list(chain.from_iterable(el or [[]] for el in lol))
# [3, 3, [], 3, [], [], 3]
答案 3 :(得分:0)
>>> result = []
>>> for l in list_of_lists:
if len(l) >0:
result += l
else:
result.append('')
>>> result
['a', 'b', '', 'c', '', '', 'd']