You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:53:10