首页 > 解决方案 > 如何同时从 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

标签: pythonpython-3.x

解决方案


这里@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
...

推荐阅读