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

如何将24小时价格列表重排为以当前小时对应元素为起始的列表?

实现24小时价格列表的循环重排

完全可以实现这个需求,用Python的话有几种简单直接的方法,下面结合你的示例给出具体实现:

方法一:列表切片拼接(最简洁)

这是Python处理这类列表重排最常用的方式,利用列表的切片特性拆分后再拼接:

import time

# 原始价格列表,对应1-24小时的价格
pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

# 获取当前系统小时(0-23,24小时制)
current_sys_hour = time.localtime().tm_hour
# 转换为你示例中的1-24小时格式(午夜0点对应24)
target_hour = 24 if current_sys_hour == 0 else current_sys_hour

# 计算起始索引:目标小时对应的列表索引(列表从0开始,所以减1)
start_idx = target_hour - 1

# 重排列表:从起始索引到末尾的元素 + 开头到起始索引前的元素
new_pricelist = pricelist[start_idx:] + pricelist[:start_idx]

print(new_pricelist)

当target_hour=13时,运行结果就是你想要的[13,14,15,16,17,18,19,20,21,22,23,24,1,2,3,4,5,6,7,8,9,10,11,12]。

方法二:用deque实现旋转(适合频繁操作场景)

如果需要多次对列表进行这类旋转操作,使用collections.deque的rotate方法效率更高:

from collections import deque
import time

pricelist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]

current_sys_hour = time.localtime().tm_hour
target_hour = 24 if current_sys_hour == 0 else current_sys_hour
start_idx = target_hour - 1

# 将列表转为deque
price_deque = deque(pricelist)
# 向左旋转start_idx次,把目标元素移到开头
price_deque.rotate(-start_idx)

# 转回列表
new_pricelist = list(price_deque)

print(new_pricelist)

两种方法都能满足你的需求,切片拼接代码更简洁,适合一次性操作;deque旋转在处理大列表或频繁操作时性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:01:00