繁体   English   中英

“TypeError:列表索引必须是整数或切片,而不是 str”

[英]"TypeError: list indices must be integers or slices, not str"

试图完成一项数据分析作业,但多次尝试后仍不断出现相同的错误

一些帮助将不胜感激。 以下是我的代码:

def is_valid_duration(duration_as_string):
try:
    duration = str(duration_as_string)
except ValueError:
    return False
else:
    duration = duration.strip("''")
    duration = duration.strip("`")
    return float(duration) > 10

filepath = "ufo-sightings.csv"


sightings_us = [row for row in ufosightings_count if row["country"] == "us" ]
fball = [row for row in sightings_us if (is_valid_duration(row["duration (seconds)"])) and (row["shape"] == "fireball")]

print(fball["datetime"], fball["state"])

我得到的错误是:

28 fball = [row for row in sightings_us if (is_valid_duration(row["duration (seconds)"])) 和 (row["shape"] == "fireball")] 中的 TypeError Traceback (最近一次调用最后一次)] 29 - --> 30 打印(fball["datetime"])

TypeError:列表索引必须是整数或切片,而不是 str

我猜 row 是某种以字符串为键的字典。 fball 是行列表(不是作为行的字典),因此 fball 需要 integer 或切片作为索引,而不是字符串。 所以你可以做

for row in fball:
   print(row["datetime"], row["state"])

或者

for ix in range(len(fball)):
  print(fball[ix]["datetime"],fball[ix]["state"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM