将列表中连续出现的相同重复项目分组 [英] Grouping the same recurring items that occur in a row from list
问题描述
例如,我们有一个像这样的列表:
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?
不是我不知道该怎么做,而是我倾向于编写很长的代码,在这种情况下,我想要一个优雅而简单的解决方案.
推荐答案
使用 itertools.groupby()
,项目会重复,因此您可能无法将所有值存储在字典中,因为item1
&重复item2
:
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
这篇关于将列表中连续出现的相同重复项目分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!