类型错误:'float'对象不可下标(不知道如何修复)



该程序运行正常,但是我收到了TypeError: 'float' object is not subscriptable,我不确定如何解决它。

这是我的代码:读取空气质量数据并返回平均空气质量字典的函数

def make_avg_pm2_dictionary():
d = {}
with open("air_data.tsv", encoding ='latin1') as fd:
for line in fd:
row=line.strip().split("t")
if row[0] in d:
key = row[0]
val1 = float(d[row[0]])
val2 = float(row[6])
temp = (val1 + val2)/2
d[key] = round(temp, 2)
elif row[0] == 'Country':
val1 = 0
else:
d[row[0]] = float(row[6])
fd.close()
return d

获取每个国家/地区的空气质量字典 (AQD) 的函数 并返回包含每个国家/地区的人口和空气质量的字典 如果该国有空气质量数据

def add_cia_population_data(dic1):
with open("cia_population.tsv", encoding='latin1') as fd:
for line in fd:
row = line.strip().split("t")
key = row[1]
if key in dic1:
temp = [row[2], dic1[key]]
d = {key: temp}
dic1.update(d)
fd.close() 
return dic1

打印出国家/地区名称、人口和 PM2 值 超过世界卫生组织1年PM2水平的阈值(以ug/m3为单位) 从图1中将长期死亡风险增加15% 打印按国家/地区姓氏排序的数据

def print_exceed_threshold(data,threshold):
for keys in data:
temp = data[keys]
if temp[1] >= threshold:
name = str(keys)
mp2 = str(temp[1])
pop = str(temp[0])
print("{0:<25} {1:<20} {2:<10}".format(name,pop,mp2))

调用所有函数

def main():
# Build dictionary from air quality file
avg_pm2 = make_avg_pm2_dictionary()
# Read in cia population and create a dictionary
# with population and average pm2 data for each country
country_data = add_cia_population_data(avg_pm2)
# print countries with air quality
# exceeding WHO's guidelines
print_exceed_threshold(country_data,35)
#run the analysis

main()

程序应该显示一些统计信息,仅此而已。

追踪:

Traceback (most recent call last):
File "<ipython-input-1-6bf5bffb30ed>", line 1, in <module>
runfile('/Users/felipe/Desktop/A05/A05.py', wdir='/Users/felipe/Desktop/A05')
File "/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 668, in runfile
execfile(filename, namespace)
File "/anaconda3/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/felipe/Desktop/A05/A05.py", line 82, in <module>
main()
File "/Users/felipe/Desktop/A05/A05.py", line 77, in main
print_exceed_threshold(country_data,35)
File "/Users/felipe/Desktop/A05/A05.py", line 60, in print_exceed_threshold
if temp[1] >= threshold:
TypeError: 'float' object is not subscriptable

从外观上看,错误在函数print_exceed_threshold()中的行if temp[1] >= threshold:中。如果 temp 不是列表,则无法调用temp[1]

print_exceed_threshold函数中,你有一个名为temp的变量,它是一个浮点数而不是数组。我会用一些断点或打印重写函数:

def print_exceed_threshold(data, threshold):
print(threshold, type(threshold)) // to see what this variable is
for keys in data:
temp = data[keys]
print(temp, type(temp))
# if temp[1] >= threshold:
#     name = str(keys)
#     mp2 = str(temp[1])
#     pop = str(temp[0])
#     print("{0:<25} {1:<20} {2:<10}".format(name,pop,mp2))

然后,您必须返回add_cia_population_data并找到导致密钥错误的行。也许在dic1.update(d)之前添加打印语句

最新更新