给定列表包含每个记录的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
答案 0 :(得分:2)
您可以尝试使用列表推导:
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个元素的元组创建字典。
答案 1 :(得分:2)
这将完成这项工作:
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)]
avg=float(sum(i[2] for i in a_list))/len(a_list)
res=[i for i in a_list if i[2]>=avg]