python - 比较两个列表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.")
推荐阅读
- php - 使用黑白蒙版蒙版 PNG 图像
- reactjs - 什么在 React 中呈现函数
- node.js - Linux上的Node JS内存泄漏
- java - 如何使用 Selenium 和 Java 在 Chrome 中禁用 cookie
- git - Git - 在 Team Explorer Visual Studio 上撤消提交
- php - 使用 codeigniter 将 2 列合二为一
- laravel - 发送确认链接并单击原始电子邮件后,使用新电子邮件更新用户的个人资料
- c# - 为什么这段代码声明一个本地函数只是为了在之后立即调用它?
- c# - 程序不显示另一个控制器的详细信息
- reactjs - 在功能组件中渲染时调用 Const 方法