python统计列表中的项目并保持其发生顺序(python count items in list and keep their order of occurrance)

编程入门 行业动态 更新时间:2024-10-26 22:22:45
python统计列表中的项目并保持其发生顺序(python count items in list and keep their order of occurrance)

鉴于:列表,例如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)]

但是有更好的方法吗? 我在这里看到了这个链接,但它将计数排序并因此打乱了顺序。

编辑:性能不是解决方案的问题,最好是内置的东西。

Given: a list, such as l=[4,4,4,4,5,5,5,6,7,7,7] Todo: get the count of an element and keep their occurrence order, e.g.: [(4,4),(5,3),(6,1),(7,3)]

I could do it with:

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)]

But is there a better way? I have seen the link here, but it sorts the counts and hence breaks the order.

Edit: performance is not an issue for the solution, preferable something built-in.

最满意答案

使用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)]

Use 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)]

更多推荐

本文发布于:2023-08-07 09:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   发生   项目   列表中   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!