我有一个列表推导式生成的列表,它stripped
通过查找哪些字符串的长度为3来按组对数据进行排序,并且我想将它们合并,以便将它们与单个长度的字符串分开放在单个列表中。
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的回答,因为它高效且简单
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个长字符串的输出:
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', '', '']
这种方式有两个列表中没有额外的拼接A
,B
作为因巴尔的解决方案提供。您还可以将其stripped
转换为生成器表达式,因此无需将两个列表保存在内存中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句