我需要找出在洛杉矶发生龙卷风最多的年份。我已经想出了如何打印它,但是如何计算并打印出龙卷风最多的年份呢?
import csv
with open('tornadoes.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
pass
else:
if row[idx['st']]=="LA":
print(row[idx['st']], row[idx['yr']])
line_count +=1
答案 0 :(得分:1)
您可以使用collections.Counter.most_common
方法:
import csv
from collections import Counter
with open('tornadoes.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader)
print(Counter(row[idx['yr']] for row in csv_reader if row[idx['st']] == 'LA').most_common())
答案 1 :(得分:0)
您可以做的是制作字典,并将每年作为关键。一旦检查完文件,就可以返回最大计数。
import csv
import operator
with open('tornadoes.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count, num_tornados = 0, {}
for row in csv_reader:
if line_count == 0:
pass
else:
if row[idx['st']]=="LA":
if row[idx['yr']] in num_tornados:
num_tornados[row[idx['yr']]] += 1
else:
num_tornados[row[idx['yr']]] = 1
line_count +=1
print(max(num_tornados.iteritems(), key=operator.itemgetter(1))[0])