python - 有没有更快的方法来做到这一点?
问题描述
所以我正在做一个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'
应该发生的是,它将返回飓风的分类名称,而是将它们分成字符,这是怎么回事?
解决方案
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: []}
推荐阅读
- php - 正则表达式 301 重定向不起作用
- php - PHP 表单/准备好的语句错误
- android - Flutter App 几乎与所有东西都不兼容?
- xamarin - 在 xamarin 表单中更改 Windows.UI.Xaml.Controls.DatePicker 弹出窗口的 FontSize
- r - 如何找到正态分布的切割点(有序数据案例) - R
- javascript - 从 javascript 添加 html 时的日期范围选择器
- android - Android 连接到 Azure 数据库
- azure - 尽管遵循了多个在线帖子中的故障排除技术,但仍无法 RDP 到 Azure VM
- html - 为什么当我将鼠标悬停在按钮上时它不起作用?
- node.js - 启动开发服务器...编译时出现警告。在 Windows 10 上,MERN 堆栈,适用于 Windows 的 GIT Bash