簡體   English   中英

如何使用 Python 函數對嵌套列表中的每個列表求和?

[英]How can I sum each list within a nested list using a Python function?

我有一組隨機的 50 名學生的考試成績。 每個學生回答了20道題,每道題的最高分是5。如何使用Python函數獲取列表中每個學生的總分?

results_sheet = []
num_of_questions = 20
num_students = 50


#generate scores for each student and append to results_sheet

for student in range(num_students):
        scores = random.choices(list(range(0,6)),k=num_of_questions)
        results_sheet.append(scores)
        
#The result here is a list of lists.

因此,如果我調用 2 個學生的結果,我將得到以下結果:

print(results_sheet[0:2])
[[4, 2, 3, 4, 2, 0, 0, 1, 2, 4, 0, 3, 5, 4, 3, 2, 5, 0, 3, 3], [5, 1, 1, 3, 2, 0, 2, 5, 3, 1, 1, 3, 5, 1, 4, 3, 2, 4, 5, 4]]

我嘗試了以下代碼,但缺少一些東西。 或者代碼可能完全錯誤:

def sum_score(results_sheet):

total = 0
for val in results_sheet:
    total = total + val
return total  

對於 2 個學生,最終結果應該是這樣的:

total_scores = [47, 55]

您可以輕松使用 numpy.sum,並將軸設置為負。

import random
import numpy

results_sheet = []
num_of_questions = 20
num_students = 50


#generate scores for each student and append to results_sheet

for student in range(num_students):
        scores = random.choices(list(range(0,6)),k=num_of_questions)
        results_sheet.append(scores)

如果你想要所有的總和:

numpy.sum(results_sheet, axis=-1)

array([43, 44, 61, 64, 52, 44, 48, 51, 36, 50, 51, 45, 56, 47, 53, 60, 53,
       45, 45, 46, 53, 54, 39, 42, 54, 67, 44, 48, 51, 58, 53, 54, 40, 52,
       62, 54, 61, 58, 47, 38, 51, 45, 50, 49, 61, 30, 50, 59, 54, 34])

因此,如果我調用 2 個學生的結果:

numpy.sum(results_sheet, axis=-1)[0:2]
array([43, 44])

首先,如果您在函數之外有一個return語句,它將不起作用。 其次,您也可以只使用 Python 中的內置sum函數:

sum_of_all = sum(scores)

然后您可以為每個學生的分數執行此操作:

results_sheet = []
num_of_questions = 20
num_students = 50


#generate scores for each student and append to results_sheet

for student in range(num_students):
        scores = random.choices(list(range(0,6)),k=num_of_questions)
        results_sheet.append(scores)

sums = [sum(result_sheet) for result_sheet in results_sheet]

sums變量將是學生的總分列表,其順序與生成的分數相同。

嘗試列表理解:

final = [sum(lst) for lst in results_sheet]

或使用map

final = list(map(sum, results_sheet))

編輯:

要使用函數:

def func(results_sheet):
    return [sum(lst) for lst in results_sheet]
print(func(results_sheet))

您必須在每個第二級列表上應用 sum(),如下所示

import random

results_sheet = []
num_of_questions = 20
num_students = 50


#generate scores for each student and append to results_sheet

for student in range(num_students):
        scores = random.choices(list(range(0,6)),k=num_of_questions)
        results_sheet.append(scores)


total = 0
for val in results_sheet:
    total = total + sum(val)
print(total)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM