简体   繁体   中英

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. 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. The compare function I created does not check for order.

eg. of final result:
random_colors = orange blue blue black
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; you can use list instead. Also, you can use zip to tell if two elements are in the same position. 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. 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")

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