1

我有一段基本的编码如下:

dict1 = [{"Name":"Ron","one":3,"two":6,"three":10}
         ,{"Name":"Mac","one":5,"two":8,"three":0}
         ,{"Name":"DUDE","one":16,"two":9,"three":2}]

print(dict1)
import operator

dict1.sort(key=operator.itemgetter("Name"))

print("\nStudents Alphabetised\n")
for pupil in dict1:
    print ("StudentName",pupil["Name"],pupil["one"],pupil["two"],pupil["three"])

我已经对其进行了整理,因此它会按字母顺序打印出人们的姓名,但是,我现在需要代码工作,以便它可以按字母顺序打印出姓名,而且它也只打印出最高分。

4

1 回答 1

4

您的分数存储在三个单独的键中;使用该max()功能选择最高的一个:

for pupil in dict1:
    highest = max(pupil["one"], pupil["two"], pupil["three"])
    print("StudentName", pupil["Name"], highest)

您可以通过将所有分数存储在一个列表中来让您的生活更轻松,而不是三个单独的键:

dict1 = [
    {"Name": "Ron", 'scores': [3, 6, 10]},
    {"Name": "Mac", 'scores': [5, 8, 0]},
    {"Name": "DUDE", 'scores': [16, 9, 2]},
]

pupil['scores'][index]然后,您仍然可以使用(其中是整数,从 0、1 或 2 中选择)来处理单个分数index,但最高分数就像max(pupil['scores']).

于 2015-10-27T09:53:34.993 回答