给定的列表包含每个记录的 3 个元素,如下所示:
a_list = [('This is A.', 00, 2.0),
('This is B.', 01, 3.0),
('This is C.', 02, 3.0),
('This is D.', 03, 1.5)]
结果应该只产生第三个元素的分数等于或大于平均值的记录。结果应该是这样的:
result = [('This is B.', 01, 3.0),
('This is C.', 02, 3.0)]
因为给定列表中第三个元素的平均值是 2.375
。
这是我一直在尝试的尝试和错误信息,见下文:
get_mean = np.mean(dict(a_list).values())
d = dict(a_list)
get_final = dict((x, y, z) for x, y, z in d.items() if z >= get_mean)
get_item = get_final.items()
get_result = sorted(get_item, reverse=True, key=lambda tup: tup[1])
return get_result
ErrorMsg --> ValueError: dictionary update sequence element #0 has length 3; 2 is required
最佳答案
您可以尝试使用列表理解:
mean = sum(x[2] for x in a_list)/len(a_list)
[x for x in a_list if x[2] >= mean]
输出:
[('This is B.', 1, 3.0),
('This is C.', 2, 3.0)]
编辑:
您收到的错误来自 dict(a_list)
。从元组列表创建字典时,每个元组应该有 2 个元素 (key, value)
。不可能创建包含 3 个元素的元组的字典。
关于python - 在列表中查找平均值,并在 Python 中返回结果分数超过平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931945/