Python 取出列表中的若干字母

2024-09-30 06:18:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为颜色的列表,我希望玩家选择4种颜色,然后我希望他们被保存到一个变量后,玩家已经选择了这些颜色这是我的代码到目前为止,我不知道如何使玩家选择的4种颜色成为一个变量

colors = ['R','Y','G','B','P','O']

print ("player 1 Create a 4 color code using", colors)
print "player 2 look away!!"
p1code = raw_input(">>> ")

if p1code == len(colors):
    print "i got the code now!"

提前感谢所有帮助你的人


Tags: 代码列表raw颜色create玩家codecolor
1条回答
网友
1楼 · 发布于 2024-09-30 06:18:04

首先,在一些print调用中需要方括号,如果您使用的是python3,则需要input而不是raw_input

colors = ['R','Y','G','B','P','O']

print("player 1 Create a 4 color code using", colors)
print("player 2 look away!!")
p1code = input(">>> ")

if p1code == len(colors):
    print("i got the code now!")

否则,在Python2.x中,您不需要方括号,如果您保持一致(当前在第一行print中,您还可以打印方括号('player 1 Create a 4 color code using', ['R', 'Y', 'G', 'B', 'P', 'O']),它可能会帮助您避免错误:

colors = ['R','Y','G','B','P','O']

print "player 1 Create a 4 color code using", colors
print "player 2 look away!!"
p1code = raw_input(">>> ")

if p1code == len(colors):
    print "i got the code now!"

其次:您已经将这四种颜色存储在p1code。当我运行上述代码时:

player 1 Create a 4 color code using ['R', 'Y', 'G', 'B', 'P', 'O']
player 2 look away!!

RBGY #what I entered

In [9]: p1code
Out[9]: 'RBGY'

因此,您可以看到字符串'RBGY'存储在变量p1code

相关问题 更多 >

    热门问题