计算有多少个二维数组中的元素超过了该数组所有元素的算术平均值。

huangapple go评论62阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月18日 17:41:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492452.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定