程序运行正常,但是我收到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水平上超过了WHO的阈值(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
答案 0 :(得分:0)
从外观上看,错误在函数if temp[1] >= threshold:
中的行print_exceed_threshold()
中。如果temp不是列表,则无法调用temp[1]
。
答案 1 :(得分:0)
在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)