【问题标题】:Print pairs of elements in a list that have the same average value as the list's average value打印列表中具有与列表平均值相同的平均值的元素对
【发布时间】:2019-05-14 09:20:30
【问题描述】:

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

import statistics

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

>>>> 4

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

【问题讨论】:

    标签: python list printing average


    【解决方案1】:

    成对迭代

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

    【讨论】:

    • 它可以在线性时间内完成,在一个排序列表上有两个迭代器。
    • 迭代次数更少,但仍然是 O(N^2)
    • 不,可以是线性的。您有一个循环,它会根据总和是否太低或太高来推进迭代器从头开始或迭代器从尾开始,直到迭代器相遇。
    【解决方案2】:

    你可以试试这个。

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

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

    【讨论】:

      【解决方案3】:
      >>> 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)]
      

      【讨论】:

        【解决方案4】:

        列表理解和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)]
        

        【讨论】:

          猜你喜欢
          • 2021-09-30
          • 2020-07-12
          • 2013-07-22
          • 1970-01-01
          • 1970-01-01
          • 2011-11-30
          • 1970-01-01
          • 1970-01-01
          • 2017-12-22
          相关资源
          最近更新 更多