Grouping the same recurring items that occur in a row from list

柔情痞子 提交于 2019-12-08 01:54:11

问题


For instance, we have a list like this:

L = ["item1", "item2", "item3", "item3", "item3", "item1", "item2", "item4", "item4", "item4"]

I want to pack them into list of tuples of the form:

[("item1", 1), ("item2", 1), ("item3", 3),... ("item1", 1)]

I've already developed an algorithm which does something similar, to get:

{item1: 2, item2: 2, ...}

(it finds all the occurrences and counts them, even if they aren't neighbours...)

However, I want it to groups only those items which have the same and are neighbours (i.e. occur in a row together), how could I accomplish this?

It's not that I don't know how to do it but I tend to write code that is long and I want an elegant and uncomplicated solution in this case.


回答1:


using itertools.groupby(), items are repeated so you might not be able to store all values in a dictionary, as item1 & item2 are repeated:

In [21]: l = ["item1", "item2", "item3", "item3", "item3", "item1", "item2", "item4", "item4", "item4"]

In [22]: for k,g in groupby(l):
    print "{0}:{1}".format(k,len(list(g)))
   ....:     
item1:1
item2:1
item3:3
item1:1
item2:1
item4:3



回答2:


This is also using itertools.groupby (a generator version):

from itertools import groupby
counts = ((k, sum(1 for _ in g)) for k, g in groupby(l))
>>> list(counts)
[('item1', 1),
 ('item2', 1),
 ('item3', 3),
 ('item1', 1),
 ('item2', 1),
 ('item4', 3)]



回答3:


python 3.2
from itertools import groupby

>>> [(i,(list(v)).count(i)) for i,v in groupby(L)]


来源:https://stackoverflow.com/questions/13565248/grouping-the-same-recurring-items-that-occur-in-a-row-from-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!