2014-05-19 25 views
0

例如,在这里我需要计算单词出现在列表中的次数,但不按频率排序,但其顺序与它们出现的顺序相似。如何获得物品的字典,但保持它们出现的顺序?

from collections import Counter 
words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"] 
c = Counter(words) 
print(c) 

所以不是:{'apples': 3, 'kiwis': 2, 'bananas': 1, 'oranges': 1}

我宁愿得到:{'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2 }

而且我并不真的需要这个“反”的方法,任何方式,将产生正确的结果是正常的我。

回答

6

您可以使用使用recipecollections.Countercollections.OrderedDict

from collections import Counter, OrderedDict 

class OrderedCounter(Counter, OrderedDict): 
    'Counter that remembers the order elements are first encountered' 

    def __repr__(self): 
     return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) 

    def __reduce__(self): 
     return self.__class__, (OrderedDict(self),) 

words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"] 
c = OrderedCounter(words) 
print(c) 
# OrderedCounter(OrderedDict([('oranges', 1), ('apples', 3), ('bananas', 1), ('kiwis', 2)])) 
相关问题