python 统计列表中的项目并保持其出现顺序
给定一个列表,比如 l=[4,4,4,4,5,5,5,6,7,7,7]。
需要做的事情是:统计每个元素出现的次数,并保持它们出现的顺序,比如:
[(4,4),(5,3),(6,1),(7,3)]
我可以用以下方法来实现:
tmpL = [(i,l.count(i)) for i in l]
tmpS = set()
cntList = [x for x in tmpL if x not in tmpS and not tmpS.add(x)]
但是有没有更好的方法呢?我看到过这个链接 这里,但它是按照计数排序的,所以打乱了顺序。
补充说明:解决方案的性能不是问题,最好是使用一些内置的功能。
3 个回答
2
如果你在用Python 2.7,可以使用collections里的Counter,它正好能满足你的需求:
http://docs.python.org/library/collections.html#collections.Counter
9
>>> import itertools
>>> [(k, len(list(g))) for k, g in itertools.groupby(l)]
[(4, 4), (5, 3), (6, 1), (7, 3)]
>>> l=[4,4,4,4,5,5,5,6,7,7,7,4,4,4,4,4]
>>> [(k, len(list(g))) for k, g in itertools.groupby(l)]
[(4, 4), (5, 3), (6, 1), (7, 3), (4, 5)]
这段话的意思是:它可以保持项目的顺序,并且还允许有重复的项目。
11
使用 groupby
:
>>> l = [4,4,4,4,5,5,5,6,7,7,7,2,2]
>>> from itertools import groupby
>>> [(i, l.count(i)) for i,_ in groupby(l)]
[(4, 4), (5, 3), (6, 1), (7, 3), (2, 2)]