2016-06-09 148 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,它在上下文中無關緊要。 –

相關問題