2012-03-27 81 views
1

可能重複:
How can I use a string with the same name of an object in Python to access the object itself?設置字符串變量名

我試圖改變名稱,取決於比賽結果的變量...

inds_EUR = [whatever] 
inds_AFR = [foo] 
inds_ASN = [other] 

pop=inds_EUR ##imagine this is the case 
for pp in ('EUR', 'AFR', 'ASN'): 
    if pp in pop: 
    paap='inds_'+str(pp)   
    break 
foos=eval(paap) 

我在試着設置「foos」作爲傳遞給這個表達式的列表

matches = [item for item in inds_vcf if item in foos] 

它的工作原理,但不知道它的危險使用該eval()函數表達式,在這裏,因爲它可能是,如果使用瓦爾() 我做正確的方式?

由於提前,

佩希

+2

你爲什麼不使用字典? – 2012-03-27 11:13:22

+1

我真的建議你看看重複的問題,因爲有(非常好)非常好的評論和答案。 – 2012-03-27 11:32:15

+0

好的,這就是我會做的。 謝謝! – peixe 2012-03-27 11:33:31

回答

7

使用字典:

inds = {'EUR': [whatever], 
     'AFR': [foo], 
     'ASN': [other]} 

foos = inds['EUR'] 
+0

即使現在我知道這是要走的路,我會看看重複。 謝謝,@eumiro – peixe 2012-03-27 11:34:24

+0

即使在封閉的問題上,至少有一個答案是很好的。 – 2012-03-27 12:05:53