阻止python打印每一个值,只打印一个?

时间:2017-05-19 11:44:15

标签: python

这是我打印代码时发生的情况:http://imgur.com/a/7nLug

我只想打印最后一行

即:'总数:891,pclass1:342(38.38%)

这是我的代码:

import csv
pclass = 0
pclass1 = [1]
pclass2 = [2]
pclass3 = [3]

pclass1_values = 0
pclass2_values = 0
pclass3_values = 0

total = 891

with open('titanic-new.csv', newline='') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter= ',')
    next(csv_reader, None)
    for row in csv_reader:
        if int(row[pclass]) in pclass1:
            pclass1_values += 1
            print('total: {}, pclass1: {} ({:.2f}%)'.format(total, pclass1_values,
                                             pclass1_values/total*100))

input('press ENTER to exit')

1 个答案:

答案 0 :(得分:2)

将print语句放在for循环之外

import csv
pclass = 0
pclass1 = [1]
pclass2 = [2]
pclass3 = [3]

pclass1_values = 0
pclass2_values = 0
pclass3_values = 0

total = 891

with open('titanic-new.csv', newline='') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter= ',')
    next(csv_reader, None)
    for row in csv_reader:
        if int(row[pclass]) in pclass1:
            pclass1_values += 1
    print('total: {}, pclass1: {} ({:.2f}%)'.format(total, pclass1_values,
                                             pclass1_values/total*100))

input('press ENTER to exit')