擅长:python、mysql、java
<p>不管怎样,我认为使用<code>csv.DictReader</code>会更容易一些:</p>
<pre><code>import csv
grades = {}
with open('grades.tsv', newline='') as csv_f:
for row in csv.DictReader(csv_f, delimiter='\t'):
fullname = row['fname'] + ' ' + row['lname']
grades[fullname] = float(row['marks'])
print(grades)
</code></pre>
<p>输出:</p>
^{pr2}$
<p>找到成绩最高的学生有点困难,因为如果打成平手,可能不止一个。下面是如何处理的方法(注意:出于测试目的,我在文件中添加了另一个学生行):</p>
<pre class="lang-none prettyprint-override"><code>Marie Curie 10
</code></pre>
<p>以及以下代码行:</p>
<pre><code>highest_grade = max(grades.values())
print('highest_grade: {}'.format(highest_grade))
tie = list(grades.values()).count(highest_grade) > 1
print('student{} with highest grade:'.format('s' if tie else ''))
for student, grade in sorted(grades.items(), key=
lambda s: s[0].split()[::-1]): # Sort by lname
if grade == highest_grade:
print(' ', student)
</code></pre>
<p>要获得以下输出:</p>
<pre class="lang-none prettyprint-override"><code>highest_grade: 10.0
students with highest grade:
Marie Curie
Evelyn Stewart
</code></pre>