python - 在 for 循环中使用 *args 不考虑变化的变量

标签 python python-3.x

我有很长的重复名称删除循环,我希望通过使用一个函数来简化事情,而不是每次都重复匹配的所有后续影响。我从以下测试用例开始,但它并没有像我预期的那样工作:

x, y = 0, 0
def testFunc(*args):
    global x, y
    for arg in args:
        if arg:
            x +=1
        else:
            y +=1
    return (x, y)

当我运行它时:

>>>testFunc(x==y,x==y,x==y)
(3,0)
>>>testFunc(x==y)
(3,1)
>>>testFunc(x!=y,x!=y,x!=y)
(3,4)

基本上,参数似乎在任何操作发生之前被转换为 bool 值。有没有办法避免这种情况?我本以为:

>>>testFunc(x==y,x==y,x==y)
(2,1)
>>>testFunc(x==y)
(2,2)
>>>testFunc(x!=y,x!=y,x!=y)
(4,3)          

最佳答案

Basically, the arguments seem to be transformed into boolean before any operation happens.

Python 在调用函数之前首先计算参数,因此这是预期的行为。两个 int 的相等性是一个 boolean。所以它首先计算 x == y 三次,每次都产生相同的结果。接下来它使用 testFunc(True, True, True) 调用函数。

Is there a way to avoid that?

您可以使其成为可调用的,从而推迟评估,方法是:

def testFunc(*args):
    global x, y
    for arg in args:
        if arg<b>()</b>:  # we call arg
            x +=1
        else:
            y +=1
    return (x, y)

然后调用它:

>>> eq = lambda: x == y
>>> neq = lambda: x != y
>>> testFunc(eq, eq, eq)
(2, 1)
>>> testFunc(eq)
(2, 2)
>>> testFunc(neq, neq, neq)
(3, 4)

因此,这里我们传递x == y的结果,我们传递一个函数,该函数在调用时计算结果x == y。因此,在调用时计算 xy 的值。

关于python - 在 for 循环中使用 *args 不考虑变化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101708/

相关文章:

python - 如何使用 Beautiful Soup 从 &lt;script&gt; 中提取内容

python - 如何在 map 函数中使用 strip

python-3.x - 完整性错误 : FOREIGN KEY constraint failed in django

python - 当您执行 class MyException(Exception) 时初始化 self.args 的原因是什么?

python - Django allauth 示例 [Errno 61] 连接被拒绝

python - JAX:为什么不使用 @jit 产生 -inf 值但使用它却没有?

python - glib.GError : Error interpreting JPEG image file (Unsupported marker type 0x05) 错误

python - “模块”对象没有属性 'DataFrame'

python - 如何在 post 查询中传递 python 列表?

python - Linux 上的多处理进程终止失败