所以我正在做一个python项目,我需要按字典组织值列表。我想知道是否有比做我正在做的事情更快的方法。
这就是我所做的,有没有更有效,更轻松的方法?
def catogorize_by_mortality(hurricanes):
damage_scale = {0: 0, 1: 100, 2: 500, 3: 1000, 4: 1e4}
hurricane_mortality_dict = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}
for hurricane in hurricanes:
current_hurricane = hurricanes[hurricane]
death_count = current_hurricane['Deaths']
if death_count > damage_scale[0] and death_count < damage_scale[1]:
hurricane_mortality_dict[0] += hurricane
elif death_count > damage_scale[1] and death_count < damage_scale[2]:
hurricane_mortality_dict[1] += hurricane
elif death_count > damage_scale[2] and death_count < damage_scale[3]:
hurricane_mortality_dict[2] += hurricane
elif death_count > damage_scale[3] and death_count < damage_scale[4]:
hurricane_mortality_dict[3] += hurricane
elif death_count >= damage_scale[4]:
hurricane_mortality_dict[4] += hurricane
else:
hurricane_mortality_dict[5] += hurricane
return hurricane_mortality_dict
# example of the hurricanes dictionary when printed
{'Cuba I': {'Name': 'Cuba I', 'Month': 'October', 'Year': 1924, 'Max Sustained Wind': 165, 'Areas Affected': ['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], 'Deaths': 90}
# this is what it returns
deaths.')
{0: ['C', 'u', 'b', 'a'
应该发生的是,它将返回飓风的名称,但将其拆分为字符,这是怎么回事?
答案 0 :(得分:0)
hurricane_mortality_dict[i]
被定义为一个列表,位于函数顶部附近:
hurricane_mortality_dict = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}
因此,在有条件的情况下,当您执行hurricane_mortality_dict[i] += hurricane
时,您尝试添加一个string
和一个list
,这会将字符串视为一个list
个字符-因此您的输出。
您需要做的就是每次更改:
hurricane_mortality_dict[i] += hurricane
收件人:
hurricane_mortality_dict[i].append(hurricane)
对于您的示例输入,则结果为:
{0: ['Cuba I'], 1: [], 2: [], 3: [], 4: [], 5: []}