python - 如何同时从 2 个列表中计数以返回 %?
问题描述
我正在编写一个函数,该函数应该返回住院的男性和女性人数。除了这部分,我的功能正常工作。
'''
each of genders and ever hospitalized directly correlate to each other,
so, Female and Yes, Male and No, and so on.
'''
ever_hospitalized = ['Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'No']
print( count_gender(genders) )
所以问题是,如何让我当前的函数返回住院的男性和女性病例的百分比?
期望的输出:
Female: 5 cases 71.43%
Male: 2 cases 28.57%
50.31% of females have been hospitalized
40.53% of males have been hospitalized
我尝试将函数中的值除以得出百分比,但它把所有这些值除以给我一个答案1
解决方案
这里@Barmar逻辑足以回答你的问题,但这里我只是为了输出模式要求,在first loop iteration
.
...
hos_mal_fem = {'Female':0, 'Male': 0}
for i,j in enumerate(ever_hospitalized):
if j == 'Yes':
hos_mal_fem[genders[i]]+=1
for i in hos_mal_fem:
string += f"{hos_mal_fem[i]/genders.count(i)*100:.2f}% {i.lowers()}s have been hospitalized\n"
return string
...
推荐阅读
- html - 如何修复“使用 CSS Clip-Path 悬停时 div 的背景问题”
- amazon-dynamodb - 如果项目在本地 dynamodb 中超过 1350+,则无法正确插入
- javascript - Nodejs无法减去数字
- python - 使用 x,y 坐标从 Pandas 数据框中删除数据并插入到另一个数据框中
- redux - redux 复杂对象不会触发更新
- terraform - Terraform - 模块之间的依赖关系
- javascript - 在 django 模板 forloop 中使用时在 javascript 中选择按钮
- r - 是否可以在 geom_text 中添加希腊字母索引?
- javascript - Meteor JS 在 findOne 函数中返回未定义的对象
- javascript - 如何在 UI5 中使用 JSON 模型属性作为 OData v4 列表绑定的路径