Python 如何检查特定整数是否在列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14608015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:57:36  来源:igfitidea点击:

How to check if a specific integer is in a list

pythonlistif-statementpython-2.7int

提问by FigNeutron

I want to know how to make an if statement that executes a clause if a certain integer is in a list.

我想知道如果某个整数在列表中,如何制作一个执行子句的 if 语句。

All the other answers I've seen ask for a specific condition like prime numbers, duplicates, etc. and I could not glean the solution to my problem from the others.

我见过的所有其他答案都要求特定条件,如素数、重复数等,但我无法从其他人那里收集到我的问题的解决方案。

采纳答案by That1Guy

You could simply use the inkeyword. Like this :

您可以简单地使用in关键字。像这样 :

if number_you_are_looking_for in list:
    # your code here

For instance :

例如 :

myList = [1,2,3,4,5]

if 3 in myList:
    print("3 is present")

回答by That1Guy

Are you looking for this?:

你在找这个吗?:

if n in my_list:
    ---do something---

Where nis the number you're checking. For example:

n你查的号码在哪里。例如:

my_list = [1,2,3,4,5,6,7,8,9,0]
if 1 in my_list:
    print 'True'

回答by Justin MacCreery

I think the above answers are wrong because of this situation:

由于这种情况,我认为上述答案是错误的:

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'  )

Would produce: Test 1 False Test 2 True

会产生: 测试 1 假 测试 2 真

A better way:

更好的方法:

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' )