2017-04-02 56 views
3

我是一個編碼的初學者。 我正在努力讓學生平均分,每個學生的名字將與每個年級的平均值相對應,並顯示學生之間的總平均分數。 這是我的代碼:如何使用Python3自動平地機

Ken = [5,8,9] 
Hiro = [10,11,20] 
Nick = [20,20,20] 

list1 = [Ken,Hiro,Nick] 

total_average = 0 
for j in list1: 
    x = 0 
    count = 0 
    for i in j: 
     x += i 
     count += 1 

    average = x/count 
    print (round(average,2)) 
    total_average += average 

final_average = total_average/len(list1) 
print (round(final_average,2)) 

和結果是:

7.33 
13.67 
20.0 
13.67 

不過,其實我是想使代碼返回,如:

13.67, {'Ken': 13.67, 'Hiro': 20.0, 'Nick': 13.67} 

我怎麼能表達這個樣子?

如果你能解釋細節,將不勝感激!

回答

1

我會建議另一種方法。首先,你的名字和成績存儲在詞典:

grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]} 

然後,你遍歷所有的字典和計算平均爲每個學生,並準備計算全球平均水平:

averages = {} 
sum_of_grades, number_of_grades = 0, 0 
for name, marks in grades.items(): 
    averages[name] = sum(marks)/len(marks) # simple arithmetic average 
    sum_of_grades += sum(marks) 
    number_of_grades += len(marks) 

最後,你計算的全球平均水平:

final_average = sum_of_grades/number_of_grades 

下面是完整的代碼,其中,計算被封裝在一個函數:

grades = {'Ken': [5,8,9], 'Hiro': [10,11,20], 'Nick': [20,20,20]} 

def compute_averages(grades): 
    averages = {} 
    sum_of_grades, number_of_grades = 0, 0 
    for name, marks in grades.items(): 
     averages[name] = sum(marks)/len(marks) 
     sum_of_grades += sum(marks) 
     number_of_grades += len(marks) 
    final_average = sum_of_grades/number_of_grades 

    return averages, final_average 

averages, final_average = compute_averages(grades) 
for name, avg in averages.items(): 
    print(name, round(avg, 2)) 
print('Final average', round(final_average, 2)) 
+0

這對我很有幫助。非常感謝你 !! – user7421972

1

嘗試使用字典而不是列表。 初始化詞典: 學生= { '紘':0, '肯':0, '尼克':0}

然後基於所計算的平均分配的值: 學生= { '紘':20.0, '肯':13.67, '尼克':13.67}

打印(學生)

+0

我明白了。謝謝 !! – user7421972

1

我建議代表學生與{name, scores, average_score}字典。您的所有學生將是一個字典列表:

students = [ 
    {'name': 'Ken', 'scores': [5, 8, 9], 'average_score': 0.0}, 
    {'name': 'Hiro', ...}, 
    ... 
] 

現在你會遍歷他們是這樣的:

for student in students: 
    # Access the attributes like this: 
    print(student['name'], student['scores']) 

    # calculate your average value ... 

    student['average_value'] = x/count 
print(students) # you can print the whole dictionary and look at the results 

與學生都在一個列表中,可以很容易地做你想要的格式 - - 只需循環所有學生,並以您想要的任何順序打印他們的名字和平均分數。

+0

我可以做到。非常感謝 !! – user7421972