python - 如何在列表理解中添加列表列表

标签 python python-3.x list-comprehension

我有一个由列表理解生成的列表,它通过查找哪些字符串的长度为 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 提供的解决方案那样额外连接两个列表 AB。您还可以将 stripped 转换为生成器表达式,这样您就不需要在内存中保存这两个列表。

关于python - 如何在列表理解中添加列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19615770/

相关文章:

python - python 将集合中的字符串分组到字典中

python - Unicode解码错误: 'charmap' codec can't decode byte 0x8d in position 386: character maps to <undefined>

将字符串列表转换为字典的 Pythonic 方法,其中奇数索引字符串作为键,偶数索引字符串作为值?

python - 在类的实例上执行类方法列表

python - 列表理解与循环——我不明白什么?

python - 印地语字体在使用 python reportlab pdf 库创建的 pdf 中不显示正确的印地语单词

python - cython嵌入后的ImportError

带有 sys.stdin 的 Python 程序出错 - Hadoop Streaming

python - 在 Python 中添加两列

python - 16331239353195370.0有什么特殊意义吗?