字典是一个好主意。用它来映射学生姓名以计算其被看到的次数。
import csv
students = {}
with open('test.csv') as fp:
next(fp) # skip header
for row in csv.reader(fp, delimiter=' ', skipinitialspace=True):
if row:
student = row[1]
if student in students:
students[student] += 1
else:
students[student] = 1
for student, count in students.items():
if count > 1:
print(student, "present mutliptle times")
它的这样一个好主意,python在collections.Counter
中实现了一个。给这个类一个迭代器,它将创建一个字典,计算该迭代器中给定值的出现次数。
import collections
with open('test.csv') as fp:
next(fp) # skip header
students = collections.Counter(row[1]
for row in csv.reader(fp, delimiter=' ', skipinitialspace=True)
if row)
for student, count in students.items():
if count > 1:
print(student, "present mutliptle times")
那么,建议的解决方案有帮助吗? – IanS