打印列表中具有与列表平均值相同的平均值的元素对

时间:2019-05-14 09:20:30

标签: python list printing average

我写了一个简单的代码来计算列表的平均值。

import statistics

x = [5, 6, 7, 0, 3, 1, 7]
print(round(statistics.mean(x)))

>>>> 4

如何获取它来打印均值相同的对?例如,[1,7]的平均值与4相同。

4 个答案:

答案 0 :(得分:0)

逐对迭代

for a, b in itertools.product(x, x):
    if (a + b) / 2 == average:
        print(a, b)

答案 1 :(得分:0)

您可以尝试一下。

let x = {
  a: 1,
  b: 2,
  c: 3  
}

let y = {
  c: 4, 
  d: 5,
  e: 6
}

let z = Object.assign(x, y)

console.log(z)

z:
{
  a:1,
  b:2,
  c:4, 
  d:5,
  e:6,
}

注意:此方法可能会创建重复的列表。

答案 2 :(得分:0)

>>> from itertools import permutations, combinations
>>> l = [5, 6, 7, 0, 3, 1, 7] 
# compute average
>>> avg = sum(l)//len(l) 
# generate all possible combinations
>>> [i for i in combinations(l, 2)] 
[(5, 6), (5, 7), (5, 0), (5, 3), (5, 1), (5, 7), (6, 7), (6, 0), (6, 3), (6, 1), (6, 7), (7, 0), (7, 3), (7, 1), (7, 7), (0, 3), (0, 1), (0, 7), (3, 1), (3, 7), (1, 7)]
>>> [(a+b)//2 for a,b in combinations(l, 2)] 
[5, 6, 2, 4, 3, 6, 6, 3, 4, 3, 6, 3, 5, 4, 7, 1, 0, 3, 2, 5, 4]
# only filter those which average to the mean of the whole list
>>> [(a,b) for a,b in combinations(l, 2) if (a+b)//2==avg]  
[(5, 3), (6, 3), (7, 1), (1, 7)]

答案 3 :(得分:0)

列表理解与itertools.combinations一起将在这里派上用场。由于您正在比较2个浮点数,因此使用阈值来确定2个数字是否足够接近(被视为相等)是很有用的(因此我们要小心浮点错误!)

from itertools import combinations
import numpy as np

def close(p, q, eps): # Use to compare if 2 float values are closer than epsilon
    return np.abs(p - q) <= eps

l = [5, 6, 7, 0, 3, 1, 7]
my_mean = np.round(np.mean(l)) # 4.0
a = [(x, y) for (x, y) in combinations(l, 2) if close(np.mean([x,y]), my_mean, 0.1)]

print(a) # [(5, 3), (7, 1), (1, 7)]