简体   繁体   English

我不知道如何使我的匹配系统正常工作

[英]I don't know how to make my matching system work

In my code, I am doing a matching system where you have two lists and the code adds one to a variable for every item in the list that is in the same index and the same item as the other list otherwise it adds one to the other variable it then puts both of the numbers in a list and prints the list. 在我的代码中,我正在执行一个匹配系统,其中您有两个列表,并且代码将一个添加到变量中,用于列表中与另一个列表具有相同索引和相同项目的每个项目,否则它将一个添加到另一个变量,然后将两个数字都放在列表中并打印该列表。

def report(ticket,winner):
kiss = []
Love = []
x = 0
y = 0 
for number in ticket:
    if number in winner:
        x +=1
    elif ticket not in winner:
            y += 1
kiss.append(x)
kiss.append(y)
print kiss

an error is like this the input is, report([1,2],[1,2,3]) I want it to add two to the x becuase two of them are in thr correct place and are the same then it needs to add one to the y because its there and not matching but it gives me out: [2,0] also if I put in report([1,3],[1,2,3]) it gives me [2,0] even thoue there not in the same index. 像这样的错误是输入,report([1,2],[1,2,3])我希望它在x上加上两个,因为其中两个在thr正确的位置且相同,则需要在y上加一个,因为它在那里并且不匹配,但是它给了我:[2,0]如果我将report([1,3],[1,2,3])放进去,它也会给我[2, 0]即使在同一索引中也没有。 That output should be [1,2]. 该输出应为[1,2]。

Based on the logic you describe there are a few problems that your code needs to implement. 根据您描述的逻辑,您的代码需要实现一些问题。 Mainly, in python the in operator checks if an item exists anywhere in a list , so for your examples that will always be True and you get that unexpected output. 主要是在python中, in运算符检查项目是否存在 list任何位置,因此对于您的示例而言,该项目始终为True并获得意外的输出。

Instead we want to check each item in the ticket list against each item in the winner list at the same index , so we must specify the index when checking each number. 取而代之的是,我们要对照相同的索引winner列表中的每个项目上检查ticket列表中的每个项目,因此在检查每个数字时必须指定索引。

Try this: 尝试这个:

def report(ticket,winner):
    kiss = []
    Love = []
    x = 0
    y = 0 

    # because we are checking different length lists, set ticket to longest list
    if len(ticket) > len(winner):
        pass
    elif len(winner) > len(ticket):
        temp = ticket
        ticket = winner
        winner = temp

    for i, number in enumerate(ticket):
        try:
            if winner[i] == number:
                x+=1
            else:
                y+=1
        except IndexError:
            y+=1

    kiss.append(x)
    kiss.append(y)
    print kiss

l1 = [1,2]
l2 = [1,2,3]
report(l1, l2) # prints [2, 1]

l1 = [1,3]
l2 = [1,2,3]
report(l1, l2) # prints [1, 2]

Are these your expected outputs? 这些是您的预期输出吗?

Hope this helps. 希望这可以帮助。

Here's a slightly shorter version using zip . 这是使用zip简短版本。

def report(ticket, winner):
    z = sum(1 for x, y in zip(ticket, winner) if x == y)
    return [z, max(len(ticket), len(winner)) - z]

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

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