英文:
Calculate how many elements of this two-dimensional array exceed the arithmetic mean of all elements of this array
问题
我需要计算一个二维数组中有多少个元素超过了该数组所有元素的算术平均值。
我需要在以下数组中执行这个操作:
array = [[1, 5, 7, 3, 2], [2, 4 ,1 ,6, 8]]
英文:
I need to calculate how many elements of a two-dimensional array exceed the arithmetic mean of all elements of this array
i need do this with this array
array = [[1, 5, 7, 3, 2], [2, 4 ,1 ,6, 8]]
答案1
得分: 2
使用 [tag:numpy]:
import numpy as np
array = [[1, 5, 7, 3, 2], [2, 4, 1, 6, 8]]
# 转换为numpy数组
a = np.array(array)
# 获取大于均值的值并计数
out = (a > a.mean()).sum()
# 5
纯Python:
from statistics import mean
avg = mean([x for l in array for x in l])
# 3.9
out = sum(1 for l in array for x in l if x > avg)
# 5
英文:
Use [tag:numpy]:
import numpy as np
array = [[1, 5, 7, 3, 2], [2, 4 ,1 ,6, 8]]
# convert to numpy array
a = np.array(array)
# get True for values above mean and count with sum
out = (a>a.mean()).sum()
# 5
In pure python:
from statistics import mean
avg = mean([x for l in array for x in l])
# 3.9
out = sum(1 for l in array for x in l if x>avg)
# 5
答案2
得分: 0
这是对问题的不同解释。假设输出应该是每个子列表中超过该子列表均值的值的数量。
lists = [[1, 5, 7, 3, 2], [2, 4, 1, 6, 8]]
for e in lists:
mean = sum(e) / len(e)
print(sum(v > mean for v in e))
输出:
2
2
英文:
Here's a different interpretation of the question. The assumption is that the output should be the number of values in each sub-list that exceed the mean for that same sub-list.
lists = [[1, 5, 7, 3, 2], [2, 4 ,1 ,6, 8]]
for e in lists:
mean = sum(e) / len(e)
print(sum(v > mean for v in e))
Output:
2
2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论