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



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

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

我该如何打印具有相同平均值的对?例如,[1,7]的平均值与4相同。

成对迭代

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

您可以尝试。

import random
while True:
    lst = random.sample(range(15), random.randint(2,10)) 
    if sum(lst)/len(lst) == 4:
        print(lst) 

nb:此方法可以创建重复列表。

>>> 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)]

列表理解与itertools.combinations一起在这里方便。由于您要比较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)]

最新更新