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

如何在for循环中用float与if语句仅提取CSV行中数值到列表?

问题场景

处理绘图数据集时遇到三个问题:数据包含表头条目、部分数据为空、数值以字符串格式存储。原代码直接循环提取索引2、3的内容到列表,但会混入无效数据。

原代码:

income=[]
fertility=[]
for row in csv:
  income.append(row[2])
  fertility.append(row[3])

print(income)
print(fertility)

为了只提取数值,写了isNumeric函数做判断:

def isNumeric(s):
   try:
      s = float(s)
      return True
   except:
      return False

但尝试的代码运行后得到空的income和fertility列表:

income=[]
fertility=[]
for row in csv:
  if isNumeric(row[2])=='True' and isNumeric(row[3])=='True':
    float(row[2])
    float(row[3])
    income.append(float(row[2]))
    fertility.append(float(row[3]))

print(income)
print(fertility)

错误原因

核心问题是布尔值和字符串比较:isNumeric返回的是布尔类型的True/False,但代码里用=='True'去判断,这永远不会成立,所以没有任何数据被添加到列表里。

另外,代码里float(row[2])这两行是无效操作,转完数值没存变量就直接丢弃了,不过这不是导致空列表的主因。

修正后的代码

方案1:修正判断条件(保留isNumeric函数)

直接用布尔值判断,不要和字符串比较,同时优化重复转float的操作:

def isNumeric(s):
   try:
      float(s)
      return True
   except:
      return False

income=[]
fertility=[]
for row in csv:
    # 直接判断布尔值,无需和字符串比较
    if isNumeric(row[2]) and isNumeric(row[3]):
        # 转一次数值存变量,避免重复转换
        inc_val = float(row[2])
        fert_val = float(row[3])
        income.append(inc_val)
        fertility.append(fert_val)

print(income)
print(fertility)

方案2:合并判断与转换(更高效)

可以把转换逻辑整合到循环里,无需单独写isNumeric函数,减少重复的float调用:

income=[]
fertility=[]
for row in csv:
    try:
        inc_val = float(row[2])
        fert_val = float(row[3])
        # 能走到这里说明两个值都是有效数值
        income.append(inc_val)
        fertility.append(fert_val)
    except (ValueError, TypeError):
        # 任意一个值无法转成float就跳过该行
        continue

print(income)
print(fertility)

额外说明

  • 空字符串""转float会抛出ValueError,会被自动过滤,符合需求。
  • 表头类字符串(比如"收入""生育率")转float也会报错,同样会被跳过,无需额外处理表头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:50:51