我如何同时从两个列表中计算,以返回a%?

2024-06-16 13:29:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个函数,它应该返回住院的男性和女性的数量。除了这个部分,我的功能还在工作

'''
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


Tags: andof函数no功能sofemaleyes
2条回答

这里@Barmar逻辑足以回答您的问题,但这里我只是为了满足输出模式要求,在^{之后添加这些行

...
    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
...

使用一本包含所有性别总数的字典。然后根据这个计算百分比

使用zip()在两个列表上同时迭代

def count_gender(genders, ever_hospitalized):
    gender_stats = {
        "Male": {"count": 0, "hospitalized": 0},
        "Female": {"count": 0, "hospitalized": 0}
    }
    for gender, hospitalized in zip(genders, ever_hospitalized):
        gender_stats[gender]["count"] += 1
        if hospitalized == "Yes":
            gender_stats[gender]["hospitalized"] += 1
    string = ''
    for type, stats in gender_stats.items():
        string += f"{type}: {stats['count']} cases {100*stats['count']/len(genders):.2f}%\n"
        string += f"{100*stats['hospitalized']/stats['count']:.2f}% have been hospitalized\n"
    return string

相关问题 更多 >