首页 > 解决方案 > 有没有更快的方法来做到这一点?

问题描述

所以我正在做一个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'

应该发生的是,它将返回飓风的分类名称,而是将它们分成字符,这是怎么回事?

标签: python

解决方案


hurricane_mortality_dict[i]被定义为一个列表,靠近函数的顶部:

hurricane_mortality_dict = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[]}

因此,在您的条件中,当您这样做时hurricane_mortality_dict[i] += hurricane,您会尝试添加 astring和 a list,它将字符串视为list字符的 a - 因此您的输出。

您需要做的就是更改每个:

hurricane_mortality_dict[i] += hurricane

至:

hurricane_mortality_dict[i].append(hurricane)

对于您的示例输入,这将导致:

{0: ['Cuba I'], 1: [], 2: [], 3: [], 4: [], 5: []}

推荐阅读