python 增量运算符在一行条件语句中有奇怪的行为

python increment operator has weird behavior in one line conditional statement

为什么idcter超过maxid时不重置为0?

maxid=9999
idcter=9999
idcter += 1 if(idcter <= maxid) else 0
print('this is good: ' + str(idcter))

idcter += 1 if(idcter <= maxid) else 0
print('now this is weird: ' + str(idcter))

idcter=10000
idcter = idcter + 1 if(idcter <= maxid) else 0
print("that's better: " + str(idcter))

输出:

this is good: 10000
now this is weird: 10000
that's better: 0

所以这是一个简单的修复,但为什么 idcter 在超过 maxid 后不会重置?

运算符优先级

idcter += 1 if (idcter <= maxid) else 0

通过以下分组可视化

idcter += (1 if (idcter <= maxid) else 0)

这意味着如果条件不成立,您 增加 0

比较
idcter = idcter + 1 if (idcter <= maxid) else 0
# ==
idcter = (idcter + 1) if (idcter <= maxid) else 0

在相同情况下,您 0 赋值给结果

顺便说一句,10000 已经超过了 maxid9999。实现这种重置增量的一种典型方法是使用模运算符。你的情况:

idcter = (idcter+1) % (maxid+1)  # 9997 -> 9998 -> 9999 -> 0 -> 1