社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

weather guy • 7 年前 • 1888 次点击  

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

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不能重置呢? 马克西德 ?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38677
文章 [ 1 ]  |  最新文章 7 年前
schwobaseggl
Reply   •   1 楼
schwobaseggl    8 年前

运算符优先级

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

你在哪里 分配 零 结果 在同样的情况下。

顺便说一句, 10000 已经超过你的 maxid 属于 9999 . 实现这种重置增量的一种典型方法是使用模运算符。在您的情况下:

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