2012-03-27 105 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