简体   繁体   English

如何比较python中的列表?

[英]How do I compare lists in python?

So I am currently working on some sort of mastermind problem and the program wants me to compare lists, I kind of got it but it keeps giving me an error: "argument of type 'int' is not iterable on line 12"所以我目前正在处理某种策划问题,程序要我比较列表,我有点明白了,但它一直给我一个错误:“'int' 类型的参数在第 12 行不可迭代”

this is what I have so far:这是我到目前为止:

import random

# These lists will be used as tests in your check_values function
computer_list = [1,2,3,5]
user_list = [2,7,3,4]
lst = []

def check_values(computer_list, user_list):
    for i in range(4):
        if user_list[i] in computer_list and user_list[i] in computer_list[i]:
            lst.extend("RED")
            return lst
        i = i + 1

check_values(computer_list, user_list)

how do I make it我该怎么做

A. stop throwing me an error despite it being a list not an int A. 尽管它是一个列表而不是一个整数,但不要再向我抛出错误

B. compare the lists and have it print based on certain conditions, the 3 colors being RED, BLACK, and WHITE, white for the number in user_list that is in computer_list but in the wrong spot, red bring for if the number in user_list that is in computer_list and the right spot, and finally black when the number in user_list that is not in computer_list B. 比较lists并根据一定条件打印,3种颜色为RED,BLACK,WHITE,白色为user_list中在computer_list中但在错误位置的数字,红色为如果user_list中的数字出现在 computer_list 和正确的位置,最后当 user_list 中的数字不在 computer_list 中时变黑

C. actually print what I want it to print and not print the thing despite the conditions of the if statement not being met C. 尽管不满足 if 语句的条件,但实际打印我希望它打印的内容而不打印该内容

? ?

You can stop the TypeError by simply changing:您可以通过简单地更改来停止 TypeError:

user_list[i] in computer_list[i] to user_list[i] == computer_list[i] user_list[i] in computer_list[i]user_list[i] == computer_list[i]

Reason being is because user_list[i] and computer_list[i] are both values not lists.原因是因为user_list[i]computer_list[i]都是值而不是列表。

This doesn't answer all your questions, but...这并不能回答您所有的问题,但是...

if user_list[i] in computer_list and user_list[i] in computer_list[i]:

When you use "user_list[i] in computer_list[i]:", you're comparing an integer to a list.当您使用“user_list[i] in computer_list[i]:”时,您将一个整数与一个列表进行比较。 What you're trying to do is see if the integers are the same.您要做的是查看整数是否相同。

Do this instead:改为这样做:

if user_list[i] in computer_list and user_list[i] == computer_list[i]:

Keep working on the rest of it yourself.继续自己处理剩下的工作。 It's easy to give up when you can't get past an error.当您无法克服错误时,很容易放弃。 Now that your error is resolved, you should be able to get the rest.现在您的错误已解决,您应该能够解决其余问题。

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

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