Python中简化变量检查与更新语句的方法咨询
更简洁的实现方式
首先要说明:直接两次调用datetime.now().hour存在潜在问题——如果代码刚好在整点前后执行,两次调用返回的小时值可能不一样,导致逻辑出错。所以先把当前小时存到临时变量里是更稳妥的做法,同时也能减少重复代码。
给你几种简洁写法:
1. 临时变量+条件判断(可读性最佳)
current_hour = datetime.now().hour if thishour != current_hour: thishour = current_hour
2. 条件表达式(一行式)
current_hour = datetime.now().hour thishour = current_hour if thishour != current_hour else thishour
3. 海象运算符简化(Python 3.8+)
如果你的Python版本在3.8及以上,可以用海象运算符一次性完成变量捕获和条件判断,省去单独定义临时变量:
thishour = (current_hour := datetime.now().hour) if thishour != current_hour else thishour
Python本身没有专门针对这种「仅当不等时赋值」的极简语法糖,但以上几种写法已经能有效减少重复代码,同时避免潜在的时间跨点问题。
内容的提问来源于stack exchange,提问作者israndy
相关产品推荐
相关产品推荐

