繁体   English   中英

如何检查号码是否与列表中的号码相同

[英]How to check whether the number is same with the number in the list

我想检查用户输入的数字是否与列表中的数字相同,以及我 select 列表中的项目使用 for 循环与数字进行比较的方式不起作用。 就像它只是遍历列表中的第一项。 即使我输入 43(示例),它仍然会打印(列表中有 43),我认为第一项是 65,这与 43 不同。

ARR = [65,75,85,95,105]

def check_number ():
    NUM = int (input ("Please enter the number you want to check with"))
    for x in range (len (arr)):   
        check == ARR [x]
    if check == ARR [x]:
        print (NUM,"is available in the list")      
    else:
        print (NUM,"is not available is the list")
check_number ()

检查一个值(包括数字和字符串的任何可散列值)是否是列表成员的更好方法是使用 Python 的内置set类型:

arr = set([65, 75, 85, 95, 105])

def check_number():
    num = int (input ("Please enter the number you want to check with"))
    if num in arr:
        print (num, "is available in the list")      
    else:
        print (num, "is not available is the list")

check_number ()

对于更大的数据集,它既更省时,也更惯用。

你可以简单地做

ARR = [65,75,85,95,105]

def check_number ():
    NUM = int (input ("Please enter the number you want to check with"))

    if NUM in ARR:
        print (NUM,"is available in the list")      
    else:
        print (NUM,"is not available is the list")
check_number ()

使用in检查数组是否包含元素是“ pythonic ”的方法。

您可以使用in关键字进行比较。

ARR = [65,75,85,95,105]

def check_number ():
    NUM = int (input ("Please enter the number you want to check with"))
    if NUM in ARR:
        print(NUM, ' is available in this list')
    else:
        print(NUM, ' is not available in this list')
check_number()

无需使用loop进行比较,因为它会traverse并将numberlist进行比较。 这是一个有点冗长的过程,而不是你可以使用in来比较numberlist 相同场景的代码如下所述:-

# Declared List named 'ARR'
ARR = [65,75,85,95,105]

# Declaration of 'check_number()' function for checking whether Number is Present in list or not
def check_number ():

    # User imput of 'Number' for Comparision
    NUM = int (input ("Please enter the number you want to check with:- "))

    # If 'Number (NUM)' is present in 'List (ARR)'
    if NUM in ARR:
        print (NUM, "is available in the list") 

    # If 'Number (NUM)' is not present in 'List (ARR)'
    else:
        print (NUM, "is not available is the list")

check_number()
# Output_1 for the above code is given below:-
Please enter the number you want to check with:- 45
45 is not available is the list
# Output_2 for the above code is given below:-
Please enter the number you want to check with:- 65
65 is available in the list

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM