Concise way to compare a variable against multiple values [duplicate]

…衆ロ難τιáo~ 提交于 2021-02-04 19:57:15

问题


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)

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)

回答1:


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)

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

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.




回答2:


if i == (3 or 5) or math.sqrt(i) == (3 or 5):

is equivalent to

if i == 3 or math.sqrt(i) == 3:

leading to 3 and 9 as results.
This because 3 or 5 is evaluated as 3 by being 3 the first non-zero number (nonzero numbers are considered True). For instance, 0 or 5 would be evaluated as 5.




回答3:


What I would recommend is instead of using "==" here, that you use "in". Here is that code:

for i in range(10):
  if i in [3,5] or math.sqrt(i) in [3,5]:
    numbers.append(i)



回答4:


You can do it using list comprehension like this.

import math as mt
a=list(range(10))
filtered_list=[x for x in a if x in [3,5] or mt.sqrt(x) in [3,5]]
print(filtered_list)



回答5:


There is one:

if i in (3,5) or math.sqrt(i) in (3,5):


来源:https://stackoverflow.com/questions/62417351/concise-way-to-compare-a-variable-against-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!