2016-09-18 76 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())