【问题标题】:python take a number of letters out of a listpython从列表中取出一些字母
【发布时间】:2017-11-07 16:22:54
【问题描述】:

我有一个名为 colors 的列表,我希望玩家选择 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!"

【问题讨论】:

  • len(colors) 是 6,而 p1code 是来自用户的字符串;在将其投入代码之前,您可能需要多考虑一下您想要实现的目标。

标签: python list


【解决方案1】:

首先,如果您使用的是 Python 3,您的一些 print 调用中需要括号,并且您需要 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!")

否则,在 Python 2.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 中。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 2011-01-29
  • 2016-04-20
  • 1970-01-01
相关资源
最近更新 更多