0

这可能很简单,但我有一个字符串列表,也对应于变量名:

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作为变量进行评估?

4

5 回答 5

5

你不想这样做。使用字典:

d = {'name1':name1, 'name2':name2}

for myvar in listname:
    myvar = d.get(myvar)
    do_stuff(myvar)
于 2013-07-15T05:10:13.567 回答
2

有时这很有用

for variable in listname:
    target = vars().get(variable)

通常最好只有一个对象列表,或者像@Haidro 建议的那样使用单独的命名空间

于 2013-07-15T05:10:12.393 回答
1
For item in string_list:
   # possibly do some string manipulation such as
   # item = item + '+= 1'
   eval(item)
   # or even exec(item)
于 2013-07-15T05:10:46.970 回答
0

看一下python的map函数:

http://docs.python.org/2/library/functions.html#map

您可以定义一个执行该切换的函数,并将该函数和列表传递给内置的 map 函数。

于 2013-07-15T05:11:27.413 回答
0

您也可以将对象放入列表中。

name1 = "some string"
name2 = "some other string"

listname =[name1, name2]

for s in listname:
    do something with s
于 2013-07-15T05:27:26.283 回答