问题
im going to need multiple if statements comparing to the same couple elements, and was wondering if there was something along these lines i could do to make the code cleaner and easier.
Example would be that this function.
def test(num):
a = [1, 2, 3]
if num == a :
return True
else :
return False
would return
>>>test(1)
True
>>>test(2)
True
>>>test(5)
False
Instead of having to write the separate if statements for 1
, 2
, and 3
.
回答1:
Use the in
operator
if num in a :
as in
def test(num):
a = [1, 2, 3]
if num in a :
return True
else :
return False
a work around would be (as suggested by Padraic)
def test(num):
a = [1, 2, 3]
return num in a
This would work because, The in operator compares if the LHS is present in the RHS and returns a boolean value respectively.
Also this is possible
test = lambda x: num in [1, 2, 3]
That is all in a single line!
回答2:
You can use in
, or check for the index
and catch the error:
num in a
will check if the item num
is in the list a
.
>>> 1 in [1, 2, 5]
True
>>> 3 in [1, 2, 5]
False
>>> 100 in range(101)
True
try
getting the index, and except
to catch the IndexError
:
def isIn(item, lst):
try:
lst.index(item)
return True
except ValueError:
return False
return False
>>> isIn(5, [1, 2, 5])
True
>>> isIn(5, [1, 2, 3])
False
来源:https://stackoverflow.com/questions/29372848/compare-to-multiple-values-in-an-if-statement