比较变量和多个值的简便方法 [英] Concise way to compare a variable against multiple values
问题描述
我一直试图了解是否可以使用类似于下面在此演示的if语句.据我了解不是吗?
I've been trying to understand if it is possible to use an if statement similar to the likes of what I have demonstrated here below. It is my understand that it is not?
for i in range(10):
if i == (3 or 5) or math.sqrt(i) == (3 or 5):
numbers.append(i)
使用此代码块,我只能得到数字 3
& 9
,而我应该得到 3、5、9
.还有另一种方法可以不列出下面的代码吗?
With this block of code I only get the numbers 3
& 9
, while I should be getting 3, 5, 9
. Is there another way of doing so without listing the code below?
for i in range(10):
if i == 3 or i == 5 or math.sqrt(i) == 3 or math.sqrt(i) == 5:
numbers.append(i)
推荐答案
您可以在 in
运算符中使用:
You can use in
operator:
for i in range(10):
if i in (3, 5) or math.sqrt(i) in (3, 5):
numbers.append(i)
或者如果您希望每个计算都在同一组结果中,则可以使用 any()
or in case you expect each of the calculations to be in the same group of results, you can use any()
results = [1, 2, ..., too long list for single line]
expected = (3, 5)
if any([result in expected for result in results]):
print("Found!")
只是个小问题, sqrt
很可能迟早会返回 float
,这种方法将来会很愚蠢,因此
Just a minor nitpick, sqrt
will most likely return a float
sooner or later and this approach will be silly in the future, therefore math.isclose()
or others will help you not to encounter float "bugs" such as:
2.99999999999999 in (3, 5) # False
这将导致您的条件失败.
which will cause your condition to fail.
这篇关于比较变量和多个值的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!