简体   繁体   English

比较两个列表python3的元素和顺序

[英]Compare elements AND order of two lists 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()

I want to compare the random_colors set to the userinput set.我想将 random_colors 集与用户输入集进行比较。 If the user enters the wrong colors or color position to the random_colors set I would like to specify wether the color is in the wrong position or is not in the random_colors set.如果用户在 random_colors 集中输入了错误的颜色或颜色位置,我想指定颜色是在错误位置还是不在 random_colors 集中。 The compare function I created does not check for order.我创建的比较函数不检查订单。

eg.例如。 of final result:最终结果:
random_colors = orange blue blue black random_colors = 橙蓝蓝黑
userinput = orange blue yellow blue用户输入 = 橙蓝黄蓝

expected - 'yellow is a wrong color' and 'blue is wrong position'预期 - “黄色是错误的颜色”和“蓝色是错误的位置”

I have not yet come to the printing bit as I am not sure how to compare the sets.我还没有来到印刷位,因为我不知道如何比较这些套装。

set does not preserve order, so you cannot tell if the user input is in a correct position; set不保留顺序,因此您无法判断用户输入是否处于正确位置; you can use list instead.您可以改用list Also, you can use zip to tell if two elements are in the same position.此外,您可以使用zip来判断两个元素是否在同一位置。 Try the following:请尝试以下操作:

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.")

In Python, a set does not preserve the order of its elements.在 Python 中, set不保留其元素的顺序。 Instead of this you could try comparing them as lists:您可以尝试将它们作为列表进行比较:

def compare(colors, userin):
  # Iterate over the index and value of each color
  # in the user input.
  for idx, color in enumerate(userin):

    # Check if the color is not the same as the color
    # at the same position in the random colors.
    if color != colors[idx]:

      # If the color exists at some other position in
      # random colors, then print that the color is
      # in the wrong position.
      if color in colors:
        print(f"{color} is wrong position")

      # Is the color is not present in the list of random
      # colors then print that the color is a wrong color
      else:
        print("{color} is a wrong color")

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

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