首页 > 解决方案 > 如何检查号码是否与列表中的号码相同

问题描述

我想检查用户输入的数字是否与列表中的数字相同,以及我使用 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

解决方案


检查一个值(包括数字和字符串的任何可散列值)是否是列表成员的更好方法是使用 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 ()

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


推荐阅读