如何在Python中将字符串连接到命令语句的末尾

2024-05-12 23:55:10 发布

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

我有一个名为nodes的类列表,其中包含类节点的实例。你知道吗

class Node:
    def __init__(self, bucketNumber ,colorONE, colorTWO,
                 colorTHREE, colorFOUR, colorFIVE):
        self.bucket = bucketNumber # index
        self.color1 = colorONE # quantity
        self.color2 = colorTWO # quantity
        self.color3 = colorTHREE # quantity
        self.color4 = colorFOUR # quantity
        self.color5 = colorFIVE # quantity

我问用户他们想要什么颜色号码。我想把int和单词“color”和数字连接起来。然后我希望能够访问这个变量,比如

valueE = (raw_input("Enter color number"))
valueE = int(valueE)
print nodes[0].color+valueE

我怎么能这样做?你知道吗


Tags: 实例self列表节点quantitycolorintnodes
3条回答

把你的颜色放在一个列表或dict中,而不是单独的变量:

self.colors = [colorONE, colorTWO, colorTHREE, colorFOUR, colorFIVE]
print node[0].colors[valueE - 1]
valueE = (raw_input("Enter color number"))
print(getattr(nodes[0], "color"+valueE))

这是未经测试的。在文档中查找getattr()。你知道吗

列一张颜色表或一本字典。(我在下面的例子中使用字典)

>>> color = {1: "X", 2: "Y"}
>>> color[1]
'X'
>>> color[2]
'Y'

相关问题 更多 >