这可能很简单,但我有一个列表,其中的字符串也对应于变量名称:
listname = ['name1', 'name2," ... ]
name1 = "somestring"
name2 = "some other string"
我希望能够做的是:
for variable in listname:
[perform some operation on the string associated with the variables
named in listname, i.e. "somestring" and then "some other string," etc.]
是否有一种简单的方法可以强制评估listname
中的字符串作为变量?
答案 0 :(得分:5)
你不想这样做。使用字典:
d = {'name1':name1, 'name2':name2}
for myvar in listname:
myvar = d.get(myvar)
do_stuff(myvar)
答案 1 :(得分:2)
有时这可能有用
for variable in listname:
target = vars().get(variable)
通常最好只有一个对象列表,或使用单独的命名空间,如@Haidro建议
答案 2 :(得分:1)
For item in string_list:
# possibly do some string manipulation such as
# item = item + '+= 1'
eval(item)
# or even exec(item)
答案 3 :(得分:0)
看一下python map函数:
http://docs.python.org/2/library/functions.html#map
您可以定义一个函数,该函数执行该切换,并将函数和列表传递给内置映射函数。
答案 4 :(得分:0)
您也可以将对象放在列表中。
name1 = "some string"
name2 = "some other string"
listname =[name1, name2]
for s in listname:
do something with s