我正在尝试使用变量作为字典中的值。我在网上搜索过,但所有答案都不是我想要的。
我创建了一个函数来查看 df 中飞机失事的特定列,以收集死亡总数除以基于给定制造商的死亡总数。这是代码:
def find_percent(make):
make_count = df1[df1['Make'] == make] # create a df with only specific make
make_total = make_count['Total.Fatal.Injuries'].sum() # add up all fatalities in col
total_fatal = df1['Total.Fatal.Injuries'].sum() #total fatalities of all makes
percent = (make_total / total_fatal) * 100 # get percentage
rounded = round(percent,2) # round
return '{} % of total deaths'.format(rounded)
当给定“boeing”时的输出为:
17.43 % of total deaths
然后将其分配给一个变量:
boeing_percent_of_deaths = find_percent('Boeing')
我正在制作一本字典,其中包含我收集的一些信息,以便于访问。例如:
first_rec = {'primary_rec' : 'B737', 'size' : 'smallest Boeing produces', 'capacity': '85 - 215'}
我正在尝试创建一个键/值:
{'percent of deahts' : boeing_percent_of_deaths }
但我无法让它输出数字。使用
first_rec['percent of deaths']
不会输出任何内容,将 []
放置在值输出 [NONE]
周围并将 ""
放置在字典中的 boeing_percent_of_deaths
周围只会输出 'boeing_percent_of_deaths'
。
(废话)
当然,我可以只输入数字作为值,但我想学习如何做到这一点,这样将来如果我需要一个可以根据新信息更改的变量,我可以对其进行编码,如果可能的话。这里是初学者,所以请不要太复杂。
def find_percent(make):
make_count = df1[df1['Make'] == make]
make_total = make_count['Total.Fatal.Injuries'].sum()
total_fatal = df1['Total.Fatal.Injuries'].sum()
percent = (make_total / total_fatal) * 100
rounded = round(percent,2)
return '{} % of total deaths'.format(rounded)
boeing_percent_of_deaths = find_percent('Boeing')
first_rec = {'primary_rec' : 'B737', 'size' : 'smallest Boeing produces', 'capacity': '85 - 215', 'reasons' : 'B737 has 2 engines, allowing redundancy in case of engine failure. It also boasts an extremely high safety record, being one of the most used aircraft in the world', 'still in production' : 'yes', 'percent of deaths': boeing_percent_of_deaths}
输出:
没什么
编辑:
我使用jupyter笔记本,所以当我使用first_rec['死亡百分比']时,下面没有任何输出。它只是为下一行代码创建一个新的代码块。 first_rec['死亡百分比'] 是我测试键值对是否有效的方式
这是我所看到的,您试图返回一个打印语句,而打印语句本身返回 None 并且它在那里打印到标准输出。所以你应该修改一下代码并给出一个返回值,然后你就可以打印它了。
def find_percent(make):
make_count = df1[df1['Make'] == make]
make_total = make_count['Total.Fatal.Injuries'].sum()
total_fatal = df1['Total.Fatal.Injuries'].sum()
percent = (make_total / total_fatal) * 100
rounded = round(percent,2)
return rounded
boeing_percent_of_deaths = find_percent('Boeing')
print('{} % of total deaths'.format(boeing_percent_of_deaths))