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

遍历含空列表的time_slots时,如何跳过元组解包步骤且不退出循环?

解决空列表跳过问题的方案

没问题,你只需要在循环里加个简单的条件判断,用continue语句就能跳过空的子列表,完全不用break(毕竟break会直接终止整个循环,不是你想要的效果)。

修改后的代码示例

import scipy.interpolate as interpolate

# 你的time_slots列表
time_slots = [[(37913.0, 0.3104248046875), (37917.0, 0.3106689453125), (37919.0, 0.31201171875)], 
              [(37945.0, 0.3123779296875), (37947.0, 0.31201171875)], 
              [], 
              [(37977.0, 0.311279296875), (37979.0, 0.310791015625), (37981.0, 0.3106689453125)], 
              [(38008.0, 0.31103515625), (38011.0, 0.31005859375), (38012.0, 0.3109130859375)], 
              [], 
              [(38039.0, 0.3095703125), (38042.0, 0.3101806640625), (38044.0, 0.3123779296875)], 
              [], [], ]

for y in range(len(time_slots)):
    current_slot = time_slots[y]
    # 检查当前子列表是否为空,为空则跳过本次迭代
    if not current_slot:
        continue
    # 非空列表才执行解包和插值操作
    x_points, y_points = zip(*current_slot)
    inrplt_func = interpolate.CubicSpline(x_points, y_points)
    # 这里可以添加你后续需要用inrplt_func做的操作,比如计算插值结果等

关键说明

  • continue是核心:它会跳过当前循环迭代里剩下的所有代码,直接进入下一次循环,完美符合你“不退出循环但跳过空列表处理”的需求。
  • 为什么要判断空列表?因为如果直接对空列表执行zip(*current_slot),会触发ValueError: not enough values to unpack (expected 2, got 0)的错误——空列表解包后没有任何值可以分给x_points和y_points。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:27:43