python - 如何使用列表理解将列表附加到现有列表

标签 python list list-comprehension

我想将项目附加到 现有 列表理解生成的列表作为单独的列表。

source = [1,2,3,4,5]
我希望结果看起来像 [[2], [4]]我尝试了以下(以及“[]”和“()”的其他疯狂组合,但一无所获)......
target = []
target.append([r for r in source if r == 2 or r == 4])
print(target)
[[2, 4]]

target = []
target.append([[r] for r in source if r == 2 or r == 4])
print(target)
[[[2], [4]]]

target = []
target.append([r] for r in source if r == 2 or r == 4)
print(target)
[<generator object <genexpr> at 0x0000022F1986E4C8>]

最佳答案

您可以使用 .extend() 而不是 .append() :

source = [1, 2, 3, 4, 5]
target = []

target.extend([r] for r in source if r == 2 or r == 4)

print(target)
# [[2], [4]]
可以使用 .extend()在这种情况下,因为它接收一个迭代作为参数。

关于python - 如何使用列表理解将列表附加到现有列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68402526/

相关文章:

python - 如何使用 sqlalchemy 查询具有值的数据库以获取另一个值?

python - 无法在 ubuntu 终端上运行 hg

python - 如何从 Python 脚本中删除所有注释?

python - 在 pyparsing 中使用 escChar 和 escQuote

python - 循环遍历日期字符串列表 : strptime outputs "Datetime.date(2011-7-5)" instead of (2011-7-5)

python - 网络爬虫的线程建议 - 使用单个列表进行调度

Python 元组而不是列表

python - 按某个键合并字典列表

python - 列表理解 Python - 继续

python - 压缩和应用函数列表和相应参数时出现类型错误