【问题标题】:Function to take a list of integers and count the highest repeated value获取整数列表并计算最高重复值的函数
【发布时间】:2019-08-31 23:52:44
【问题描述】:

需要一个函数来获取整数列表并返回最高的重复值。

例如:取 [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2] 并返回 (2,5) 因为值 2 有 5 个副本。

【问题讨论】:

  • 欢迎来到 SO。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。这不是讨论论坛或教程服务。您应该花一些时间通过the Tutorial 练习这些示例。它将向您介绍 Python 为解决您的问题所提供的工具。

标签: python arrays list


【解决方案1】:

您可以使用 Counter 轻松完成此操作。

from collections import Counter

a = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]

def count_duplicates(list_of_integers):
  a = Counter(list_of_integers)
  return a.most_common()[0]

count = count_duplicates(a)

print(count)

输出给你 (2, 5)

【讨论】:

    【解决方案2】:

    内置maxsetcount方法:

    def countMax(arr):
        item = max(set(arr), key=arr.count)
        return (item, arr.count(item))
    
    print(countMax([4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]))
    

    打印(2, 5)

    【讨论】:

      【解决方案3】:

      我们可以利用元组来跟踪最高的重复值,如下所示:

      def find_highest_repeated(input_list):
          counter = {}
          highest_repeated = (0, 0, )
      
          for item in input_list:
              counter[item] = counter[item] + 1 if counter.get(item) is not None else 1
              if counter[item] > highest_repeated[1]:
                  highest_repeated = (item, counter[item], )
      
          return highest_repeated
      
      find_highest_repeated([4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]) # (2, 5)
      

      希望有帮助!

      【讨论】:

        【解决方案4】:

        您可以使用defaultdict 来实现:

        from collections import defaultdict
        
        def highest_repeated_value(nums):
          cache = defaultdict(int)
          for i in nums:
            cache[i] += 1
          return max(cache.items(), key=lambda x: x[1])
        
        
        nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
        print(highest_repeated_value(nums))
        

        请注意,如果nums = [4, 4, 4, 4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2] 则有five 4sfive 2s。但是,结果将是(4, 5),即five 4s

        如果您使用numpy 并且列表包含所有非负ints,则可以使用numpy.bincounts

        import numpy
        
        def highest_repeated_value(nums):
            counts = numpy.bincount(nums)
            num = numpy.argmax(counts)
            val = numpy.max(counts)
            return num, val
        
        nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
        print(highest_repeated_value(nums))
        

        如果你只是想在 python 中工作而不使用numpycollections.Counter 是一个很好的处理方式。

        from collections import Counter
        
        def highest_repeated_value(nums):
          return Counter(nums).most_common()[0]
        
        nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
        print(highest_repeated_value(nums))
        

        【讨论】:

        • 有没有办法使用 numpy 来完成这个?
        猜你喜欢
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 1970-01-01
        • 2020-08-12
        • 2012-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多