给定:一个列表,例如 l=[4,4,4,4,5,5,5,6,7,7,7] Todo:获取元素的数量并保持其出现顺序,例如: [(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)]
但是有没有更好的办法呢?我已经看到链接 here , 但它对计数进行排序,因此打乱了顺序。
编辑:性能不是解决方案的问题,最好是内置的东西。
最佳答案
使用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)]
关于python计算列表中的项目并保持它们的出现顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7902924/