2017-05-24 75 views
0

选择一个变量在蟒如果我有一系列列表如:结合字符串和Integer在Python

room1 = [1, 0, 1, 1] 
room2 = [1, 0, 0, 1] 
room3 = [0, 0, 1, 1] 

然后,我有一个整数和字符串,如:

location = 2 
type = "room" 

如何组合变量type中的字符串和location中的整数来选择相关列表,然后使用列表中该位置的值。例如这样的事情:

room2 = [1, 0, 0, 1] 
location = 2 
type = "room" 
currentPos = type + location 

print "%s" % currentPos[location] 

如果我结合typelocation我得到一个错误的那些字符串,其余的整数。如果我将位置更改为字符串并将两个字符串组合在一起,Python将以字符串的形式输出currentPos输出,然后我不能使用位置来选择列表值,因为这需要整数。

location = "2" 
type = "room" 
currentPos = type + location 
print "%s" % currentPos 

>>room 

是否有适用于使用从变量的字符串,并有蟒蛇使用字符串输出明确选择另一个变量的名称的方法吗?

+3

你有一个很好的理由不使用词典? –

回答

-1
currentPos = type + str(location) 

或者

currentPos = '%s%d' % (type, location) 

或者

currentPos = '{:s}{:d}'.format(type, location) 
+0

感谢您的信息。我已经根据上述和现在的功能重写了我的代码。 – thal0k