我在这里的百分比显然无法正确显示结果,我不确定为什么,

时间:2018-12-02 23:21:34

标签: python python-3.x csv percentage

这是我所拥有的-它显示但百分比不正确-ps。这是一个有关csv文件的文件,其中包含了泰坦尼克号上的人员的信息-我正尝试找出所有在职的泰坦尼克号上女性的百分比-谢谢您的帮助!

    import csv


       f = open('titanic.csv', 'r');
       lecteur = csv.reader(f, delimiter=',', quotechar='"')
       count=0
       total = 0
       for ligne in lecteur:
            total=total+1
       if ligne[3]=="female":
           count=count+1

        perc=(count/(total-1)) *100


        print("Total:", total-1)
        print("Pourcentage des femmes:", perc )

1 个答案:

答案 0 :(得分:1)

if语句必须位于for循环内。另外,您可以使用len()函数来获取total,而无需自己增加变量。

total = len(lecteur) - 1 #subtract the header line
for ligne in lecteur:
    if ligne[3] == "female":
        count += 1

perc = count/total * 100