簡體   English   中英

python計算列表中的項目並保持其出現順序

[英]python count items in list and keep their order of occurrance

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

但有更好的方法嗎? 我在這里看到了這個鏈接,但它對計數進行了排序,因此打破了順序。

編輯:性能不是解決方案的問題,更可取的是內置的東西。

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

如果您使用的是Python 2.7,則可以使用Collection from collections,它完全符合您的要求:

http://docs.python.org/library/collections.html#collections.Counter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM