【问题标题】:How to do nothing in conditional statement while Python list comprehension? [duplicate]Python列表理解时如何在条件语句中什么都不做? [复制]
【发布时间】:2019-12-03 14:29:27
【问题描述】:

事情是这样的:

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!"]

正如您在输出中看到的那样,我有我不想拥有的第一个和最后一个项目。

我尝试了各种方法,例如删除 else 语句(这是不可能的),将 0 替换为 pass 语句(它也不起作用)。

list 理解的同时,是否有可能在list 中使用条件获得刚需要的项目?还是只有filter 函数才有可能?

需要的输出:

[2]

【问题讨论】:

  • 预期输出是什么?
  • 只需删除if 语句中的else 部分:[x for x in lst if x == 2]
  • @HarshaBiyani 问题帖已更新。
  • 如果一定要加点什么,可以试试pass或者continue
  • 你的“需要的输出”是你说你不想拥有的确切输出..可能想检查一下

标签: python python-3.x filter conditional-statements list-comprehension


【解决方案1】:

试试这个:

lst = [1, 2, 3]
i = [x for x in lst if x == 2]
print(i)

输出:

[2]

你没有正确使用列表推导,if 语句应该在for 循环之后。请参阅list comprehensions in Pythonits documentation 了解更多信息。

在更改问题之前,这是答案:

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!"]

Quotation marks inside a string, explanation.

【讨论】:

    【解决方案2】:

    您将if 放在错误的位置。试试这个:

    lst = [1, 2, 3]
    i = [x for x in lst if x == 2]
    print(i)
    # [2]
    

    【讨论】:

    • 为什么投反对票?这实际上与已接受答案的 edited version 相同,只是当我写它时 edits 不存在......如果有的话,可以说出我的答案启发了被接受的...
    • 这是正确的。 Norok2 在这里表明,在没有 else 的情况下,列表推导的格式有点不同——“if”放在最后。
    猜你喜欢
    • 1970-01-01
    • 2016-01-05
    • 2014-06-20
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多