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

如何使用Python min()函数时排除空字符串''和'0'结果?

处理含空字符串与'0'的寿命列表,获取有效最小值

问题说明

从CSV文件读取的life_expectancy列表包含空字符串''和字符串'0',需要忽略这两类值计算最小值。

尝试直接调用min()未得到有效结果:

index1 = (life_expectancy.index(min(life_expectancy,)))
print(life_expectancy[index1])

使用key=int参数时触发报错:

index1 = (life_expectancy.index(min(life_expectancy, key=int)))

报错内容:

ValueError: invalid literal for int() with base 10: ''

原因是空字符串无法转换为整数,导致key函数执行失败。

解决方案

方法1:先过滤无效值再计算

先筛选出既非空字符串也非'0'的有效元素,再对有效列表求最小值,最后获取其在原列表中的索引:

# 过滤掉空字符串和'0'
valid_life = [item for item in life_expectancy if item not in ('', '0')]
# 获取有效最小值
min_valid = min(valid_life, key=int)
# 找到原列表中的对应索引
index1 = life_expectancy.index(min_valid)
print(life_expectancy[index1])

注意:如果原列表存在多个相同的最小值,index()仅返回第一个匹配项的索引。

方法2:在key函数中排除无效值

无需提前过滤,通过自定义key函数给无效值分配极大值,确保它们不会被选为最小值:

def life_key(value):
    if value in ('', '0'):
        # 返回无穷大,让无效值不会成为最小值候选
        return float('inf')
    return int(value)

min_valid = min(life_expectancy, key=life_key)
index1 = life_expectancy.index(min_valid)
print(life_expectancy[index1])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:00:49