我有一个由列表理解生成的列表,它通过查找哪些字符串的长度为 3 来根据组对 stripped
中的数据进行排序,我想合并它们以便在与单个长度字符串分开的单个列表。
stripped = ['a,b', 'c,d', 'e', '', 'f,g', 'h', '', '']
lst = [[i.split(',')] if len(i) is 3 else i for i in stripped]
print(lst)
#[[['a', 'b']], [['c', 'd']], 'e', '', [['f', 'g']], 'h', '', '']
我想生成 [[['a', 'b'], ['c', 'd'],['f', 'g']], 'e', '', 'h', '', '']
而不是
如果可能,我如何通过单一列表理解实现这一点?
编辑:
已接受 @HennyH's答案是因为它的高效和简单
最佳答案
l = [[]]
for e in stripped:
(l[0] if len(e) == 3 else l).append(e)
>>>
[['a,b', 'c,d', 'f,g'], 'e', '', 'h', '', '']
或者为 3 个长字符串匹配 OP 的输出:
for e in stripped:
l[0].append(e.split(',')) if len(e) == 3 else l.append(e)
>>>
[[['a', 'b'], ['c', 'd'], ['f', 'g']], 'e', '', 'h', '', '']
这样就不会像 Inbar 提供的解决方案那样额外连接两个列表 A
、B
。您还可以将 stripped
转换为生成器表达式,这样您就不需要在内存中保存这两个列表。
关于python - 如何在列表理解中添加列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19615770/