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

如何用更Pythonic的方式将秒数拆分生成含整小时及剩余秒数的列表

Pythonic实现方案

核心用Python内置的divmod函数一次性拿到商和余数,配合列表乘法实现,代码简洁易读:

示例代码

def split_seconds(total_seconds: int) -> list[str]:
    hour_count, remainder = divmod(total_seconds, 3600)
    result = ['3600'] * hour_count
    if remainder:
        result.append(str(remainder))
    return result

# 测试
print(split_seconds(11000))  # 输出:['3600', '3600', '3600', '200']
print(split_seconds(7200))   # 输出:['3600', '3600']

如果偏好更短的一行写法,也可以直接写成:

total_seconds = 11000
res = ['3600'] * (total_seconds // 3600) + ([str(total_seconds % 3600)] if total_seconds % 3600 else [])

写法优势

  • 用内置divmod避免重复计算商和余数,执行效率更高
  • 列表乘法代替循环生成重复的整小时元素,代码更简洁符合Python习惯
  • 自动兼容整小时无余数的边界场景

内容的提问来源于stack exchange,提问作者Julian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:45:03