如何在列表理解中添加列表列表 [英] How to add list of lists in a list comprehension
问题描述
我有一个列表推导式生成的列表,它通过查找哪些字符串的长度为3来按组对stripped
中的数据进行排序,并且我想将它们合并,从而将它们与单个列表分开单长度字符串.
I have a list which is produced by a list comprehension and it sorts the data in stripped
according to groups by finding which strings have a length of 3 and I want to merge them so that are in a single list separately from single length strings.
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', '', '']
如果可能,我如何使用单列表理解来实现这一目标?
How can I achieve this with a Single list-comprehension if possible?
因为高效和简单而被 @HennyH的答案接受了
accepted @HennyH's answer because of its high efficiency and simplicity
推荐答案
l = [[]]
for e in stripped:
(l[0] if len(e) == 3 else l).append(e)
>>>
[['a,b', 'c,d', 'f,g'], 'e', '', 'h', '', '']
或者匹配OP的3个长字符串的输出:
Or to match the OP's output for the 3 long strings:
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
转换为生成器表达式,这样就不必将两个列表保存在内存中.
This way there is no additional concatenation of two lists A
,B
as Inbar's solution provided. You can also turn stripped
into a generator expression so you don't need to hold the two lists in memory.
这篇关于如何在列表理解中添加列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!