python计算列表中的项目并保持它们的出现顺序

标签 python

给定:一个列表,例如 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/

相关文章:

python - 静音 music21 警告

python - 散点图上的标称/分类轴

python - 如何在 keras 模型中对某些输出进行比其他输出更多的惩罚?

python - 将数据从网络应用程序发送到 ipython 笔记本

python - map with lambda vs map with function - 如何将多个变量传递给函数?

python - 加权平均日期时间,关闭但仅限某些月份

python - 通过空子类对对象进行分类是 Pythonic 吗?

python - 隐藏刻度标签值但保留轴标签

python - 在不需要的地方使用递归是不好的做法吗?

python - 如何使用 Matplotlib 绘制 3D 扇区?