字典是一個好主意。用它來映射學生姓名以計算其被看到的次數。
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