Python:2.6:尝试构建像 exec('if' + varname + '< 1.0:') 这样的语句

发布于 2024-12-21 09:23:56 字数 428 浏览 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'

有没有办法使这样的变量语句起作用?

My goal here is to have the same if statement in a for loop were the variable name changes
Those statements are in a function in a different file: the appropriate Import scheme
as been set.

Examples:

for i in range(0,10):

    myvar = ''
    myvar = myvar + str(i)
    exec('if' + myvar + '< 0:')
`do something`

It say about the do something part "unexpected ident "
I remove the ident and it say; KeyError: 'myvar1'
I tried using this instead

if vars()[myvar] < 0:

    do something 

It gives me the same KeyError: 'myvar1'

Is there a way to make such a variable statement to work ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淑女气质 2024-12-28 09:23:56

您将字符串“if 0 < 0:”传递给 exec() 函数。这不是一个语法上有效的构造——它缺少受控套件。您可能会考虑:然而

if eval(myvar) < 0:
    do_something()

,作为更一般的观点,在生产程序中动态评估变量名几乎总是错误的。通常最好使用字典将键映射到值(这就是它们的用途,并且避免使用 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:

if eval(myvar) < 0:
    do_something()

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()).

情域 2024-12-28 09:23:56

因此,您实际上应该重构代码以将 myvarN 存储为列表。然后你可以这样做:

for element in myvars:
    if element < 0:
        doSomething(element)

So you should really just refactor your code to store myvarN as a list. Then you can just do:

for element in myvars:
    if element < 0:
        doSomething(element)
浪推晚风 2024-12-28 09:23:56

如果您尝试执行以下操作:

var1 = 10
var2 = 12
var3 = 18

for i in range(10):
  if locals().get('var%d' % i, 0) > 10:
    # something here for the conditions that pass.

该代码应该可以工作。与您所做的最大区别是我在 locals() 上调用了 .get() ,这样如果您尝试测试一个不存在的变量,它就会返回与某事。老实说,这是一种奇怪的方法,但有时奇怪的方法是必要的。

If you're trying to do something like this:

var1 = 10
var2 = 12
var3 = 18

for i in range(10):
  if locals().get('var%d' % i, 0) > 10:
    # something here for the conditions that pass.

That code should work. The biggest difference from what you'd done is that I called .get() on locals() 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文