簡體   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()

我想將 random_colors 集與用戶輸入集進行比較。 如果用戶在 random_colors 集中輸入了錯誤的顏色或顏色位置,我想指定顏色是在錯誤位置還是不在 random_colors 集中。 我創建的比較函數不檢查訂單。

例如。 最終結果:
random_colors = 橙藍藍黑
用戶輸入 = 橙藍黃藍

預期 - “黃色是錯誤的顏色”和“藍色是錯誤的位置”

我還沒有來到印刷位,因為我不知道如何比較這些套裝。

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

在 Python 中, set不保留其元素的順序。 您可以嘗試將它們作為列表進行比較:

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