Python列表理解时如何在条件语句中不执行任何操作? [英] How to do nothing in conditional statement while Python list comprehension?
问题描述
这是东西:
lst = [1, 2, 3]
i = [x if x == 2 else "I don't need that!" for x in lst]
print(i)
输出:
["I don't need this item!", 2, "I don't need this item!"]
在输出中可以看到,我有不想拥有的第一项和最后一项。
As you can see in output I have the first and last items which I want to not have.
我尝试了各种操作,例如删除 else
语句(不可能),替换 0 $ c $带有
pass
语句的c>(也不起作用)。
I tried various things, such as to remove else
statement (it's not possible), replace 0
with pass
statement (it's not working either).
是否甚至可以在其中获得所需的项目 list
有条件,而 list
有条件吗?还是只能使用 filter
函数?
Is it even possible to get just needed items in list
with conditionals while list
comprehensions? Or it's only possible with filter
function?
需要的输出:
[2]
推荐答案
尝试一下:
lst = [1, 2, 3]
i = [x for x in lst if x == 2]
print(i)
输出:
[2]
您尚未正确使用列表理解功能,如果
语句应位于 for
循环之后。请参见 Python中的列表理解或其文档以获取更多信息。
You haven´t used list comprehension correctly, the if
statement should come after the for
loop. See list comprehensions in Python or its documentation for more information.
在更换风琴之前,这是答案:
Before the quetions had been changed, this was the answer:
lst = [1, 2, 3]
i = [x if x == 2 else "I don't need this item!" for x in lst]
print(i)
输出:
["I don't need this item!", 2, "I don't need this item!"]
这篇关于Python列表理解时如何在条件语句中不执行任何操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!