我怎样才能在列表理解中不添加任何内容?

2024-09-28 17:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个列表理解:

[2 * x if x > 2 else add_nothing_to_list for x in some_list]

我需要“add_nothing_to_list”部分(逻辑的其他部分)字面上是“nothing”。

Python有办法做到这一点吗?特别是,有没有一种方法可以说a.append(nothing)保持a不变。这是编写通用代码的一个有用特性。


Tags: to方法inadd列表forifsome
1条回答
网友
1楼 · 发布于 2024-09-28 17:26:41

把条件移到最后

[2 * x for x in some_list if x > 2]

引用List Comprehension documentation

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

在本例中,表达式是2 * x,然后是for语句,for x in some_list,然后是if语句,if x > 2

这种理解是可以理解的,就像这样

result = []
for x in some_list:
    if x > 2:
        result.append(x)

相关问题 更多 >