python - 在列表中查找平均值,并在 Python 中返回结果分数超过平均值

标签 python list dictionary mean

给定的列表包含每个记录的 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/

相关文章:

python - Flask View 引发 "AttributeError: ' 函数'对象没有属性"

python - 如何使用Conda共享一组python模块

python - 该函数接受输入字符串 x 列表并返回整数 ptr

python - 如何查找列表中的数字序列

c# - 向 C# 列表索引器添加编译时安全性 - 这可能吗?

python - 重命名列表数据框中元素的最有效方法

python - 强制开发人员使用预定义的属性列表作为函数参数

python - 如何检查一个 pandas 列中列表中的所有元素是否存在于另一 pandas 列中

python - 嵌套字典Python中的分组数据

excel - 字典循环每个键的值