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

スコアは 3 つの個別のキーに保存されます。max()関数を使用して最高のものを選択します。

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

3 つの個別のキーではなく、すべてのスコアをリストに保存することで、作業が楽になります。

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

その後も個々のスコアにpupil['scores'][index](indexは整数、0、1、または 2 から選択) を指定できますが、最高のスコアは のように単純max(pupil['scores'])です。

于 2015-10-27T09:53:34.993 に答える