You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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):
    userchoice = input("Enter your color choice: {}: ".format(i+1))
    userinput.append(userchoice)


def compare():
    # 存储完全不存在的错误颜色
    wrong_colors = set()
    # 存储颜色存在但位置不匹配的颜色
    position_error_colors = set()
    for idx, user_color in enumerate(userinput):
        if user_color not in random_colors:
            wrong_colors.add(user_color)
        else:
            if user_color != random_colors[idx]:
                position_error_colors.add(user_color)
    # 输出对应提示
    for color in wrong_colors:
        print(f"{color}是错误颜色")
    for color in position_error_colors:
        print(f"{color}位置错误")


compare()

效果验证

你给出的示例场景(random_colors = ['orange','blue','blue','black']、userinput = ['orange','blue','yellow','blue'])运行后输出如下:

yellow是错误颜色
blue位置错误

完全符合预期需求。

内容的提问来源于stack exchange,提问作者Sponge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:36:07