提问人:adewole 提问时间:8/23/2023 最后编辑:Peter Mortensenadewole 更新时间:8/24/2023 访问量:107
如何获取列表中元素的平均值?
How can I get the average of the elements in a list?
问:
我正在尝试在 Python 中迭代嵌套列表并计算每个内部列表中元素的平均值。以下是我正在使用的嵌套列表的示例:
student_marks = [
['Name', ['A', 'B', 'C', 'D', 'E']],
['Shiloh', [41, 34, 45, 55, 63]],
['Shawn', [42, 23, 34, 42, 53]],
['Lewis', [32, 23, 23, 54, 67]],
['Pete', [23, 82, 23, 63, 34]],
['Rock', [21, 23, 25, 56, 56]]
]
我试图通过对元素求和并除以内部列表的长度来计算平均值,但我遇到了一个错误,指出整数对象不可迭代。这是我的代码:
for i in student_marks[1:]:
marks_in_C = i[1][2]
print(marks_in_C)
average = sum(marks_in_C) / len(marks_in_C)
print(average)
答:
2赞
Sand
8/23/2023
#1
如果您尝试操作的值始终位于嵌套循环的最后一个单元格中,则会像这样工作:
for student_value in student_marks:
name = student_value[0]
marks = student_value[1]
avg_score = sum(marks)/len(marks)
print(f"{name}'s avg score is {avg_score}")
评论
0赞
Sand
8/23/2023
你可以更进一步,将每个人的分数记录为字典(假设我们称之为 report = {}),并在每次迭代时使用 report[name] = avg_score,这样所有分数都可以在字典中按名称“搜索”
3赞
InSync
8/23/2023
一个更惯用的方式是.for name, mark in student_marks:
1赞
craigmj
8/23/2023
#2
student_marks = [['Name', ['A', 'B', 'C', 'D', 'E']],
['Shiloh', [41, 34, 45, 55, 63]],
['Shawn', [42, 23, 34, 42, 53]],
['Lewis', [32, 23, 23, 54, 67]],
['Pete', [23, 82, 23, 63, 34]],
['Rock', [21, 23, 25, 56, 56]]
]
s = [ i[1][2] for i in student_marks[1:]]
print(sum(s)/len(s))
您可以使用列表推导式 (https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) 创建仅包含所需元素的新列表。在此示例中,我只从记录中提取“C”列,并将其提取到一个名为“s”的新列表中,然后我只得到 和 的平均值。sum
len
0赞
nwoodw
8/23/2023
#3
您当前一次只在 marks_in_C 变量中存储一个值。尝试将它们放在列表中,然后在运行循环后对列表执行操作。
marks_in_C = []
for i in student_marks[1:]:
marks_in_C.append(i[1][2])
print (marks_in_C)
这将按照您的预期工作:
average = sum (marks_in_C)/ len(marks_in_C)
print(average)
0赞
AquaticHoney
8/23/2023
#4
student_marks = [['Name', ['A', 'B', 'C', 'D', 'E']],
['Shiloh', [41, 34, 45, 55, 63]],
['Shawn', [42, 23, 34, 42, 53]],
['Lewis', [32, 23, 23, 54, 67]],
['Pete', [23, 82, 23, 63, 34]],
['Rock', [21, 23, 25, 56, 56]]
]
student_marks.pop(0)
for i in student_marks:
avg_marks = sum(i[1]) / len(i[1])
print(avg_marks)
这似乎是你想要的
评论
1赞
Codist
8/24/2023
#5
开发一个更通用的解决方案可能是一个好主意,通过该解决方案,您可以按主题(例如,C)获得平均值,而不是使用常量索引。
像这样的东西:
student_marks = [['Name', ['A', 'B', 'C', 'D', 'E']],
['Shiloh', [41, 34, 45, 55, 63]],
['Shawn', [42, 23, 34, 42, 53]],
['Lewis', [32, 23, 23, 54, 67]],
['Pete', [23, 82, 23, 63, 34]],
['Rock', [21, 23, 25, 56, 56]]
]
def get_average_by_subject(table, subject):
try:
index = table[0][1].index(subject)
values = [scores[index] for _, scores in table[1:]]
return sum(values) / len(values)
except Exception:
pass
print(get_average_by_subject(student_marks, 'C'))
输出:
30.0
评论
np.array
sum
i[1]
i[1][2]
i
['Shiloh', [41, 34, 45, 55, 63]]
1