【问题标题】:Sort a list with duplicate items by the number of duplicate occurrences按重复出现的次数对包含重复项的列表进行排序
【发布时间】:2016-02-17 14:20:50
【问题描述】:

我有

list1 = ["one", "two", "two", "three", "five", "five", "five", "six"]

输出应该是

list2 = ["five" , "two", "one", "three" , "six"]
  • "five" 是第一个元素,因为在 list1 中出现的次数最多 (3)
  • "two" 是第二个元素,因为在 list1 中的出现次数次之(2)
  • "one""three" 和 "six" 的出现次数相同 (1),所以它们在我的 list2 中排在最后——只要它们在“五”之后,它们并不重要“两个”。list2 = ["five" , "two", "six", "three", "one"]list2 = ["five" , "two", "three", "one", "six"] 或任何其他变体都是可以接受的。

【问题讨论】:

    标签: python list


    【解决方案1】:

    您可以使用列表理解和Counter:

    from collections import Counter
    print([element for element,count in Counter(list1).most_common()])
    

    输出:

    ['five', 'two', 'three', 'six', 'four', 'one']
    

    【讨论】:

    • 这正是我所需要的。 @donkey-kong 谢谢!
    【解决方案2】:

    您可以使用itertools.groupby() 获取按出现次数排序的列表:

    from itertools import groupby
    from operator import itemgetter
    
    grouped = [(uniq, len(list(dups)))
               for uniq, dups in groupby(sorted(list1))]  # group & count
    grouped.sort(key=itemgetter(1), reverse=True)  # sort by occurrence
    list2 = list(map(itemgetter(0), grouped))
    

    如果重复项已经在 list1 中分组(就像您的问题一样),那么您可以放弃 sorted() 电话。 groupby() 可能比 collections.Counter() 更有效(内存/时间方面)——如果它对您的情况很重要,请测量它。

    【讨论】:

      【解决方案3】:

      使用计数器集合这是它的特定用途

      https://docs.python.org/2/library/collections.html

      【讨论】:

        【解决方案4】:
        a= ["one", "two", "two", "three", "four" , "five", "five", "five", "six"]
        dic={}
        for name in a:
            if name in dic:
                dic[name]=dic[name]+1
            else:
                dic[name]=1
        
        keyList=[]
        valueList=dic.values()
        valueList.sort()
        valueList.reverse()
        
        def get_Value(dic,value):
            for name in dic:
                if dic[name] == value:
                    del dic[name]
                    return name
        
        
        for num in valueList:
            keyList.append(get_Value(dic,num))  
        
        print keyList
        

        【讨论】:

          猜你喜欢
          • 2017-06-20
          • 2020-04-14
          • 2019-11-13
          • 2023-03-13
          • 2015-11-14
          • 2023-04-08
          • 1970-01-01
          • 2015-08-20
          • 2017-05-25
          相关资源
          最近更新 更多