如何在Python中使用字符串值作为变量名?

时间:2016-06-09 05:33:49

标签: python string python-2.7 variables

假设我有以下列表:

 function listshops(callback)
        {   
         client.connection.query('select * from shop',function(err,rows){
           if(rows.length>0)
           { 
             for(var i=0;i<rows.length;i++)
             {   
               (function(i){
               var shopIdFetched = rows[i].shopId;
               client.connection.query('select * from image where shopId=?',shopIdFetched,function(err,data){
                 if(data.length > 0){
                  var result = rows[i].image = JSON.stringify(data);   
                    }
                  });
               })(i);
              }
              console.log(rows[i]);

             }

          });
        }

和一个字符串

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

我想使用字符串name = 'fruit' 来访问列表及其内容。在这种情况下,它应该是name。我将使用fruit来迭代列表。为:

name

3 个答案:

答案 0 :(得分:8)

你可以这样使用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)

答案 1 :(得分:5)

我不明白你到底想要实现的目标是什么,但这可以使用eval来完成。我不建议使用eval。如果你告诉我们你最终想要达到的目标,那会更好。

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

编辑

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

答案 2 :(得分: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,但是我们会在以后保存它! 我希望这有帮助!