Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我如何同时从两个列表中计算,以返回a%?_Python_Python 3.x - Fatal编程技术网

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

Python 我如何同时从两个列表中计算,以返回a%?,python,python-3.x,Python,Python 3.x,我正在写一个函数,它应该返回住院的男性和女性的数量。除了这个部分,我的功能还在工作 ''' 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( co

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

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

的答案。使用一个字典来保存每个性别的所有总数。然后根据这个计算百分比

使用
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
这里的逻辑足以回答您的问题,但这里我只是为了满足输出模式需求,在
第一次循环迭代之后添加这些行

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

我提供的2个函数已经计算了性别,有没有一种方法可以只在提供的函数中添加几行?谢谢。@James它需要
zip
循环来计算住院人数,所以在同一个循环中只计算性别更简单。