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

时间:2019-02-10 23:07:16

标签: python python-2.x

我知道有一种更简单的方法可以做到这一点。它应该像是一个“西蒙”游戏,您可以从列表中生成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)

1 个答案:

答案 0 :(得分:0)

您快到了。您的问题是尝试修改原始的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? ")

现在,您应该找到一种检查答案是否正确的方法。