首页 > 解决方案 > 比较两个列表python3的元素和顺序

问题描述

import random

colors = ['blue', 'yellow', 'green', 'orange', 'black']
random_colors = (random.choices(colors, k=4))

print(f'\nWelcome to the color game! your color options are: \n{colors}\n')


userinput = []
for i in range(0, 4):
    print("Enter your color choice: {}: ".format(i+1))
    userchoice = str(input())
    userinput.append(userchoice)


def compare():
    set_colors = set(random_colors)
    set_userin = set(userinput)
    result = set_userin - set_colors
    print(result)


compare()

我想将 random_colors 集与用户输入集进行比较。如果用户在 random_colors 集中输入了错误的颜色或颜色位置,我想指定颜色是在错误的位置还是不在 random_colors 集中。我创建的比较函数不检查订单。

例如。最终结果:
random_colors = 橙蓝蓝黑用户输入
= 橙蓝黄蓝

预期 - “黄色是错误的颜色”和“蓝色是错误的位置”

我还没有来到印刷位,因为我不确定如何比较这些集合。

标签: pythonlistcompare

解决方案


set不保留顺序,因此您无法判断用户输入是否处于正确位置;你可以list改用。此外,您可以使用zip来判断两个元素是否在同一位置。尝试以下操作:

import random

colors = ['blue', 'yellow', 'green', 'orange', 'black']
random_colors = random.choices(colors, k=4)

user_colors = [input(f"Color {i+1}: ") for i in range(4)]

for u, r in zip(user_colors, random_colors):
    if u not in random_colors:
        print(f"{u} is a wrong color.")
    elif u != r:
        print(f"{u} is in a wrong position.")

推荐阅读