我写了一个简单的代码来计算一个列表的平均值。
import statistics
x = [5, 6, 7, 0, 3, 1, 7]
print(round(statistics.mean(x)))
>>>> 4如何打印具有相同平均值的配对?例如,1,7的平均值与4相同。
发布于 2019-05-14 17:23:47
成对迭代
for a, b in itertools.product(x, x):
if (a + b) / 2 == average:
print(a, b)发布于 2019-05-14 17:30:01
你可以试试这个。
import random
while True:
lst = random.sample(range(15), random.randint(2,10))
if sum(lst)/len(lst) == 4:
print(lst) 注意:此方法可能会创建重复的列表。
发布于 2019-05-14 17:34:37
>>> 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)]https://stackoverflow.com/questions/56126928
复制相似问题