如何检查某个特定整数是否在列表中
我想知道怎么写一个if语句,让它在某个整数在列表里时执行某个操作。
我看到的其他回答都在问一些特定的条件,比如质数、重复数字等等,我从那些回答中没有找到解决我问题的方法。
4 个回答
-2
我觉得上面的回答是错的,因为出现了这种情况:
my_list = [22166, 234, 12316]
if 16 in my_list:
print( 'Test 1 True' )
else:
print( 'Test 1 False' )
my_list = [22166]
if 16 in my_list:
print( 'Test 2 True' )
else:
print( 'Test 2 False' )
会产生: 测试 1 错 测试 2 对
更好的方法是:
if ininstance(my_list, list) and 16 in my_list:
print( 'Test 3 True' )
elif not ininstance(my_list, list) and 16 == my_list:
print( 'Test 3 True' )
else:
print( 'Test 3 False' )
8
你是在找这个吗?:
if n in my_list:
---do something---
这里的 n
是你要检查的数字。例如:
my_list = [1,2,3,4,5,6,7,8,9,0]
if 1 in my_list:
print 'True'
59
你可以简单地使用 in
这个关键字。就像这样:
if number_you_are_looking_for in list:
# your code here
例如:
myList = [1,2,3,4,5]
if 3 in myList:
print("3 is present")