PYTHON 需要帮助简化 - 从预设列表生成随机项目

PYTHON Need help simplifying - generating random items from a pre-set list

我知道有一种更简单的方法可以做到这一点。它应该是一个类似于 "Simon" 的游戏,您可以从列表中生成 5 种随机颜色,然后用户输入颜色。每转一圈它都应该保持第一种颜色相同并添加一种新的随机颜色,这就是我的麻烦所在。任何帮助将不胜感激!

import random
# Create a list of colors.
colors = ['Yellow', 'Green', 'Red', 'Blue']

# Generate random colors from the list. 
color1 = random.choice(colors)
color2 = random.choice(colors)
color3 = random.choice(colors)
color4 = random.choice(colors)
color5 = random.choice(colors)


# Simon displays the 5 color choices, adding 1 each turn. 

print "Simon says: ", color1
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2, color3
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2, color3, color4
raw_input ("What did Simon say? ")

print "Simon says: ", color1, color2, color3, color4, color5
raw_input ("What did Simon say? ")

我的第一次尝试看起来像这样,但也没有用:

# Create a list of colors.
colors = ['Yellow', 'Green', 'Red', 'Blue']


# Display the color list, adding one random color each turn. Prompt the
# user to enter the colors after each is added.
for i in range (5):
    import random
    color = random.choice(colors)

    print "Simon says: " ,color

    raw_input ("What did Simon say? ")
    colors.append(colors)
    print "Simon says: " , (color)

你快到了。您的问题是尝试修改您原来的 4 色列表。只需为游戏初始化一个新的空列表:

# Create a list of colors.
colors = ['Yellow', 'Green', 'Red', 'Blue']

# Display the color list, adding one random color each turn. Prompt the
# user to enter the colors after each is added.
chosen_colors = []
for i in range (5):
    import random
    color = random.choice(colors)
    chosen_colors.append(color)
    print "Simon says: " ,chosen_colors
    raw_input ("What did Simon say? ")

现在你应该想办法检查答案是否正确。