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

为何这段Python代码在Jupyter NB正常运行却在Google Colab报错?

问题分析与解决

报错内容翻译

ValueError: max() arg is an empty sequence
中文释义:值错误:传入max()函数的参数是空序列

问题根源

你的代码逻辑是只将daily_climb中大于20的元素计算差值后加入displacement_lst,再取列表最大值。如果在Google Colab中运行时,daily_climb里没有任何大于20的元素,displacement_lst就会是空列表,此时调用max()必然触发这个错误。

你提供的代码里daily_climb明明有多个符合条件的元素,大概率是你在Colab中实际运行的代码里,这个列表被误修改了——比如不小心删除了部分元素,或者替换成了全≤20的数值。

修复方案

方案1:给max()添加默认值(Python 3.4+支持)

直接给max()函数设置default参数,空列表时返回指定默认值,不影响原有逻辑:

def max_displacement():
    daily_climb = [30, 21, 33, 77, 44, 45, 23, 45, 12, 34, 55]
    displacement_lst = []
    
    for x in daily_climb:
        if x > 20:
            diff = x - 20
            displacement_lst.append(diff)
            
    return max(displacement_lst, default=0)  # 空列表时返回0,可按需修改
   
solution2 = max_displacement()
print(solution2)

方案2:先判断列表是否为空

手动检查displacement_lst状态,空列表时返回默认值:

def max_displacement():
    daily_climb = [30, 21, 33, 77, 44, 45, 23, 45, 12, 34, 55]
    displacement_lst = []
    
    for x in daily_climb:
        if x > 20:
            diff = x - 20
            displacement_lst.append(diff)
            
    if not displacement_lst:
        return 0  # 空列表时返回默认值,可按需修改
    return max(displacement_lst)
   
solution2 = max_displacement()
print(solution2)

最后,务必检查你在Colab中运行的代码,确认daily_climb列表的内容和你提供的完全一致,避免因误编辑导致列表无符合条件的元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:56:08