2016-09-18 32 views
-3

目標是獲取兩個列表,查看是否有任何元素匹配,以及它們是否每次都添加1以進行計數。第一個列表是5個元素的列表,第二個列表是用戶輸入。它不起作用,我做錯了什麼?它必須使用函數來完成,請幫助。使用函數檢查常見元素的Python函數

userask = input("Enter a few numbers to try win the lotto:  ") 


def count_correct(list1,list2): 


    count = 0 
    for r in list2: 
     if list1 in list2: 
       count += 1 

    return count 
+0

我敢肯定,你的一些代碼丟失。提示:從項目中創建'set'對象並使用它們的交集來獲取公共元素,然後使用'len'來計算它們 –

+0

我們被告知我們不允許使用這些問題我們需要使用函數 –

回答

-2

您的代碼在這裏不完整。但我認爲這種改變應該會對你有所幫助。

不要使用if list1 in list2:,使用if r in list2:

+0

計數不增加我試過但計數保持0 –

1

需要先通過空間分割的數字(如你所願),並變成一個列表:

userask = input("Enter a few numbers to try win the lotto:  ") 
userlist = userask.split() 

然後,你可以用它做任何一組像這樣:

result = len(set(list1) & set(userlist)) 

在僅非重複常見的將被計算或解決您的for循環像這樣:

def count_correct(list1,list2): 

    count = 0 
    for r in list2: 
     if r in list1: 
      count += 1 

    return count 
0

要實現你的計數功能,你可以使用sumgenerator expression

def count_correct(list1, list2): 
    # each True in the generator expression is coerced to int value 1 
    return sum(i in list1 for i in list2) 

注意,使用將消除重複在你的清單,如果有的話,這將給予不正確的結果。


要捕捉您的輸入列表,你可以這樣做:

userask = input("Enter a few numbers to try win the lotto (separated by spaces):  ") 

list1 = map(int, userask.split())