我有很长的重复名称删除循环,我希望通过使用一个函数来简化事情,而不是每次都重复匹配的所有后续影响。我从以下测试用例开始,但它并没有像我预期的那样工作:
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
的相等性是一个 bool
ean。所以它首先计算 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
。因此,在调用时计算 x
和 y
的值。
关于python - 在 for 循环中使用 *args 不考虑变化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101708/