简体   繁体   English

错误的循环比较列表

[英]Erroneous loop comparing lists

I am trying to write a script that will take as input lottery numbers and also a lotto ticket, then see how many matches there are and print this. 我正在尝试编写一个脚本,将其作为输入彩票号码和彩票,然后查看有多少匹配项并打印出来。

I am however having troubles with my loop that compares the elements from two lists. 但是,我在比较两个列表中的元素的循环时遇到了麻烦。 What am I doing wrong? 我究竟做错了什么?

READ: Serious newbie here. 阅读:认真的新手。

#sets LOTTO ticket line
def makeOneTicket(myNums):
    for i in range(0,6):
        nr = input()
        myNums.append([nr])
    return myNums

def makeTicketList(numTix, ticList): 
    ticket = []
    for i in range(0,numTix):
        ticket = makeOneTicket(ticket)
        ticList.append([ticket])

        if i == numTix -1:    
            print "Done."
        else:
            print "Next ticket."
    return ticList

def checkTicketMatch(list1, list2):
    counter = 0
    for element in list1:
        if element in list2:
            counter = counter + 1
    return counter



winNums = []
myNums = []
ticList = []
print "Please enter winning LOTTO numbers: "
makeOneTicket(winNums)

print "-----------------------------"
print winNums
print "-----------------------------"

print "How many tickets do you have?: "
numTix = input()

print("Enter your lotto numbers one by one: ")
ticList = makeTicketList(numTix, ticList)

matches = 0
matches = checkTicketMatch(winNums, ticList[0])
print matches

A few issues with Python: Python的几个问题:

When you do this line : 当您执行以下操作时:

myNums.append([nr])

That means your ticket will not look like [1, 1, 2, 3, 5], but [[1], [1], [2], [3], [5]] . 这意味着您的票证看起来不会像[1、1、2、3、5],而是[[1], [1], [2], [3], [5]]

Instead, you should do 相反,你应该做

myNums.append(nr)

This doesn't directly cause your bug, but later on, when you do 这不会直接导致您的错误,但是稍后,当您这样做时

ticList.append([ticket])

... your list of tickets also becomes [[ticket], [ticket]], so then when you do your comparison, you're comparing a list of size one (containing a ticket) to a ticket. ...您的票证列表也将变为[[ticket],[ticket]],因此,当您进行比较时,您正在将一个大小为1(包含票证)的列表与票证进行比较。

That is the source of your problem. 那就是问题的根源。

Another issue with your code: there are two ways of making a function that makes a list, by creating it: 您的代码的另一个问题:通过创建列表的函数,可以通过两种方法进行创建:

def make_list():
    result = []
    result.append(3)
    return result

my_list = make_list()

or passing it inline, as you would often do in C: 或内联传递它,就像在C语言中通常那样:

def fill_list(_list):
    _list.append(3)

my_list = []
fill_list(my_list)

...you seem to have functions that do both at the same time, which works, but is overkill. ...您似乎具有同时执行这两个功能的功能,这些功能虽然有效,但过分杀伤力。

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

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