2016-06-09 141 views
0

假设我有列表如下:如何在Python中使用字符串值作为变量名?

candy = ['a','b','c'] 
fruit = ['d','e','f'] 
snack = ['g','h','i'] 

和一个字符串

name = 'fruit' 

我想用串name访问列表和它的内容。在这种情况下,它应该是fruit。我将使用name作为迭代列表。正如:

for x in name: 
    print x 
+3

你可以用eval来做到这一点,但我建议使用字典来保存这些列表。 – ayhan

+0

更多的重点是:你**不要在python **中使用字符串值作为变量名称。 Python有强大的工具和数据结构,可以用它们代替。 – spectras

+0

@spectras请给我参考我可以用来代替它的数据结构。 –

回答

5

我不明白你在试图这样做是为了实现什么,但是这可以通过使用eval完成。虽然我不推荐使用eval。如果你告诉我们你最终想达到的目标会更好。

>>> candy = ['a','b','c'] 
>>> fruit = ['d','e','f'] 
>>> snack = ['g','h','i'] 
>>> name = 'fruit' 
>>> eval(name) 
['d', 'e', 'f'] 

编辑

查看由Sнаđошƒаӽ对方的回答。这将是更好的方式去。 eval存在安全风险,我不建议使用它。

5

您可以使用globals()像这样:

for e in globals()[name]: 
    print(e) 

输出:

d 
e 
f 

如果你的变量碰巧在一些局部范围内可以使用locals()

OR你可以创建你的字典和访问:

d = {'candy': candy, 'fruit': fruit, 'snack': snack} 
name = 'fruit' 

for e in d[name]: 
    print(e) 
+3

严重的是,使用这个而不是'eval',尤其是如果传入的值将来自用户 - 这可以让用户有效地运行所有具有**巨大安全风险的事情。虽然使用“dict”会更好。 – metatoaster

+0

@metatoaster我认为你的评论应该在OP的问题上,你不觉得吗? ;-) 谢谢。 –

+0

确实。但是这个问题及其答案是一个教给人们如何在脚下自杀的详细解释的例子。 – spectras

1

使用字典!

my_dictionary = { #Use {} to enclose your dictionary! dictionaries are key,value pairs. so for this dict 'fruit' is a key and ['d', 'e', 'f'] are values associated with the key 'fruit' 
        'fruit' : ['d','e','f'], #indentation within a dict doesn't matter as long as each item is separated by a , 
      'candy' : ['a','b','c']   , 
         'snack' : ['g','h','i'] 
    } 

print my_dictionary['fruit'] # how to access a dictionary. 
for key in my_dictionary: 
    print key #how to iterate through a dictionary, each iteration will give you the next key 
    print my_dictionary[key] #you can access the value of each key like this, it is however suggested to do the following! 

for key, value in my_dictionary.iteritems(): 
    print key, value #where key is the key and value is the value associated with key 

print my_dictionary.keys() #list of keys for a dict 
print my_dictionary.values() #list of values for a dict 

词典默认情况下是没有顺序的,这可能会导致上下行的问题,但也有解决这个方法使用多维数组或orderedDicts但我们会保存这个在稍后的时间! 我希望这有助于!

+1

有些时候,最好的答案是最难使用的:-) –

+0

@BhargavRao但更多的时候,最简单的答案是最难接受的! – TheLazyScripter

+0

当使用dict的方法已经显示在现有的答案中时,你的答案还会显示什么?另外,你的答案有一些无关紧要的东西,例如orderedDict,它在上下文中无关紧要。 –

相关问题