因此,我有一个csv (https://ufile.io/y4nr9),它由“,”分隔,并包含“名称”、“幸存”、“性别”等列。我想找出没有存活的男性的百分比,并打印统计数据。到目前为止,我的代码如下:
import csv
reader = csv.reader(open('titanic-new_alphabetized.csv'), delimiter= ',')
filtered = filter(lambda p: 'male' == p[3], reader)
dict = []
input('press ENTER to exit')发布于 2017-05-17 03:31:08
您可以过滤它们并在Python 3中像这样计算统计数据:
import csv
total, survived = 0, 0
with open('titanic-new_alphabetized.csv', newline='') as csvfile:
for row in filter(lambda p: 'male'==p[3], csv.reader(csvfile, delimiter= ',')):
total += 1
if int(row[0]):
survived += 1
print('total: {}, survived: {} ({:.2f}%)'.format(total, survived,
survived/total * 100))输出:
total: 577, survived: 109 (18.89%)发布于 2017-05-17 03:00:42
您正在使用list语法创建字典。
您应该使用dict = {}。
发布于 2017-05-17 03:02:52
您还应该以变量的形式打开文件,这样以后就可以轻松地关闭它。
或者使用with ... as打开文件。
https://stackoverflow.com/questions/44014749
复制相似问题