Python:2.6:尝试构建像 exec('if' + varname + '< 1.0:') 这样的语句
我的目标是在变量名称更改的情况下在 for 循环中具有相同的 if 语句 这些语句位于不同文件的函数中:适当的导入方案 已设置。
示例:
for i in range(0,10):
myvar = ''
myvar = myvar + str(i)
exec('if' + myvar + '< 0:')
`do something`
它说的是“做某事”部分“意外的身份” 我删除了身份,它说;关键错误:'myvar1' 我尝试使用它,
if vars()[myvar] < 0:
do something
它给了我相同的 KeyError: 'myvar1'
有没有办法使这样的变量语句起作用?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将字符串“if 0 < 0:”传递给 exec() 函数。这不是一个语法上有效的构造——它缺少受控套件。您可能会考虑:然而
,作为更一般的观点,在生产程序中动态评估变量名几乎总是错误的。通常最好使用字典将键映射到值(这就是它们的用途,并且避免使用 exec() 和 eval())。
You are passing the string "if 0 < 0:" to the exec() function. This is not a syntactically valid construct -- it's missing the controlled suite. You might consider instead:
As a more general point, however, dynamic evaluation of variable names is almost invariably the wrong thing to do in a production program. You are usually better to use a dict to map keys to values (that's what they are for, and you avoid the use of exec() and eval()).
因此,您实际上应该重构代码以将 myvarN 存储为列表。然后你可以这样做:
So you should really just refactor your code to store myvarN as a list. Then you can just do:
如果您尝试执行以下操作:
该代码应该可以工作。与您所做的最大区别是我在
locals()
上调用了.get()
,这样如果您尝试测试一个不存在的变量,它就会返回与某事。老实说,这是一种奇怪的方法,但有时奇怪的方法是必要的。If you're trying to do something like this:
That code should work. The biggest difference from what you'd done is that I called
.get()
onlocals()
so that if you try to test a non-existent variable it comes back with something. This ... is an odd approach, tbh, but sometimes odd approaches are necessary.