简体   繁体   中英

Find if the values in two different lists match or not in python

Good evening! In my project I have two button to choose to go left or right. The correct path is the one stored in the self.path variable. In my def function I'm triying to print if the path is correct or not but I'm having problem with it: the first if statement doesn't print "correct" when the button left is pressed at the beginning and the second if statement also doesn't work (it should match self.path and self.chance stored values everytime a button is pressed and tell me if the answer is right or not) Can someone help me?

        self.path = ["left", "left", "right"]         

        self.chance = []
 
        self.button_left  = tk.Button(self, text="left", command=self.left)
        self.button_right = tk.Button(self, text="right", command=self.right)
        self.button_left.grid(row=0, column=1)
        self.button_right.grid(row=0, column=0)

    def left(self):
         self.chance.append("left")   
         self.function()
        

    def right(self):
        self.chance.append("right")
        self.function()
        

    def function(self):
        if len(self.chance) == 0 and self.chance[0] == self.path[0]:         
            print("correct")     
        else:
            print("wrong")      
           
        if len(self.chance) >= 1:
            item_list += 1
            self.chance[item_list] == self.path[item_list]
            print("correct")
        else:
            print("wrong")

For the first if statement, it is impossible that self.chance is an empty list ( len(self.chance) == 0 ) AND that self.chance[0] exists. Therefore, the first if statement will always print wrong .

For the second if statement, there is a line of code in there which says self.chance[item_list] == self.path[item_list] , which is simply a comparison which does not do anything by itself. I assume this comparison is the one you want to put in your if statement, instead of len(self.chance) >= 1 ?

I think what you want function() to do is verify that path matches chance up to the length of chance . This is easy to accomplish by slicing path equal to the length of chance and then simply comparing the result:

def function():
    if self.chance == self.path[:len(self.chance)]:
        print("correct")
    else:
        print("wrong")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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