python:如何计算列表中的项
这可能很简单,但我有一个列表,其中的字符串也对应于变量名:python:如何计算列表中的项,python,variables,Python,Variables,这可能很简单,但我有一个列表,其中的字符串也对应于变量名: 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,
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
中的字符串作为变量进行求值?有时这很有用
for variable in listname:
target = vars().get(variable)
通常,最好只是有一个对象列表,或者像@Haidro建议的那样使用一个单独的名称空间您不想这样做。使用字典:
d = {'name1':name1, 'name2':name2}
for myvar in listname:
myvar = d.get(myvar)
do_stuff(myvar)
看看python映射函数:
您可以定义一个函数来进行切换,并将函数和列表传递到内置映射函数中。您也可以将对象放入列表中
name1 = "some string"
name2 = "some other string"
listname =[name1, name2]
for s in listname:
do something with s
@Haidro在这种情况下,OP将是
eval
ing硬编码变量名,eval
真的那么危险吗?当然,如果eval
永远不会接受用户输入,那么它就不会比代码本身更危险,或者我遗漏了什么吗?@SethMMorton如果他自己定义了列表,他就可以完成[name1、name2等](而不是字符串)。这个名单可能来自其他地方,但是呃:p@Haidro同意。。。我不是说在这种情况下,eval
是最好的方法,但我是说,在你的代码中包含eval
可能不会危及无辜儿童的安全:)海德罗*:p。谢谢你的推荐:D
name1 = "some string"
name2 = "some other string"
listname =[name1, name2]
for s in listname:
do something with s