簡體   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