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)]更多推荐
发布评论