【问题标题】:How can I use min() without getting "0" or "" for an answer?我如何使用 min() 而不会得到 \"0\" 或 \"\" 的答案?
【发布时间】:2022-11-23 23:42:54
【问题描述】:

我正在尝试在来自 .csv 的列表中使用 min,其中一些值是''我怎么能忽略那些,还有“0”

我试过了

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

当我尝试时,一无所获:

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

我有: ValueError:以 10 为底的 int() 的无效文字:''

因为这是函数在最小值处处理的值

【问题讨论】:

  • 你能提供一个示例输入吗?
  • 我不认为有一种简单的方法可以使用min 在一行代码中做到这一点。
  • 您可以先过滤您的 life_expectancy 列表,如:life_expectancy = [value for value in life_expectancy if value != "0" and value != ""]

标签: python python-3.x list minimum


【解决方案1】:

我不认为有一种简单的方法可以使用min 在一行代码中做到这一点。

避免 0 值的一种方法是在 min 之前调用 filter。然后,为了避免无效值,您可以围绕 int 编写一个包装器,它在无效值时返回 0。

def int_or_zero(s):
    try:
        return int(s)
    except ValueError:
        return 0

def nonzero_min(seq):
    return min(filter(None, map(int_or_zero, seq)))

print( nonzero_min(['hello', '0', '12', '3', '0', '5', '']) )
# 3

【讨论】:

    【解决方案2】:

    尝试这个:

    new_life_expectancy = [value for value in life_expectancy if value != '' and value != '0']
    

    这将删除 ''0 的所有实例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多