【问题标题】:Using an 'or' operator in a basic python list comprehension在基本的 Python 列表理解中使用“或”运算符
【发布时间】:2021-03-08 23:18:33
【问题描述】:

问题:如何在 python 列表推导中使用 OR?

我希望输出 0-99 之间的任何数字,该数字可以被 5 或 7 整除且没有余数。我有以下代码:

numbers = [x for x in range(99) if x % 5 == 0 if x % 7 == 0]

但这会返回:0、35、70 这是可以被 5 和 7 整除的数字。我也试过了:

numbers = [x % 5 == 0 or x % 7 == 0 for x in range(99)]

但这会为每个数字返回 True 或 False,我希望自己获取数字。使用这个:

numbers = [x for x in range(99) if x % 5 == 0 or if x % 7 == 0]

引发语法错误。

我查看了以下页面,但无法理解如何应用这些解决方案。它们每个似乎都为我想要的解决方案提供了细微差别,但并不是我想要的。

datacamp.com/community/tutorials/python-list-comprehension

programiz.com/python-programming/list-comprehension

use-of-or-operator-in-python-lambda-function

not-comprehending-list-comprehension-in-python

is-there-a-binary-or-operator-in-python-that-works-on-arrays

how-to-convert-this-my-code-into-a-list-comprehension

python-list-comprehension-with-multiple-ifs

【问题讨论】:

  • 您与numbers = [x for x in range(99) if x % 5 == 0 or if x % 7 == 0] 如此亲密,您需要一个表达式而不是两个ifs。
  • if x % 5 == 0 if x % 7 == 0 这将像嵌套的 if 一样工作。

标签: python python-3.x list list-comprehension or-operator


【解决方案1】:

不要使用另一个if

numbers = [x for x in range(99) if (x % 5 == 0) or (x % 7 == 0)]
print(numbers)

因为if是一个语句,那些是表达式,然后做or并使用if简写检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2022-12-13
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 2022-11-24
    相关资源
    最近更新 更多