【发布时间】: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
【问题讨论】:
-
您与
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