【问题标题】:How to get the most common element from a list in python [duplicate]如何从python中的列表中获取最常见的元素[重复]
【发布时间】:2015-09-26 11:10:54
【问题描述】:

我有一个如此处所示的列表。 a=[1936,2401,2916,4761,9216,9216,9604,9801] 我想获得具有更多重复项的值。在这里是'9216' 我怎样才能得到这个值?谢谢

【问题讨论】:

    标签: python list python-3.x


    【解决方案1】:

    您可以为此使用collections.Counter:

    from collections import Counter
    
    a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801] 
    
    c = Counter(a)
    
    print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
    [(9216, 2)] # a set containing the element, and it's count in 'a'
    

    来自文档:

    【讨论】:

      【解决方案2】:

      有两种标准库方法可以做到这一点:

      statistics.mode:

      from statistics import mode
      most_common = mode([3, 2, 2, 2, 1])  # 2
      most_common = mode([3, 2])  # StatisticsError: no unique mode
      

      collections.Counter.most_common:

      from collections import Counter
      most_common, count = Counter([3, 2, 2, 2, 1]).most_common(1)[0]  # 2, 3
      most_common, count = Counter([3, 2]).most_common(1)[0]  # 3, 1
      

      两者在性能方面是相同的,但是当没有唯一的最常见元素时,第一个会引发异常,而第二个也会返回频率。

      【讨论】:

        【解决方案3】:

        这是另一个没有使用计数器的

        a=[1936,2401,2916,4761,9216,9216,9604,9801]
        frequency = {}
        for element in a:
            frequency[element] = frequency.get(element, 0) + 1
        # create a list of keys and sort the list
        # all words are lower case already
        keyList = frequency.keys()
        keyList.sort()
        print "Frequency of each word in the word list (sorted):"
        for keyElement in keyList:
            print "%-10s %d" % (keyElement, frequency[keyElement])
        

        【讨论】:

          【解决方案4】:

          https://docs.python.org/2.7/library/collections.html#counter

          从集合导入计数器 计数器(a).most_common(1)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-04-10
            • 2021-05-11
            • 1970-01-01
            • 2011-04-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多