2

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.

ekad
  • 14,436
  • 26
  • 44
  • 46
  • `item1: 1, item2:1, item3:3....item1: 1` would not be a dictionary... (it has more than one of the same key) – Andy Hayden Nov 26 '12 at 12:59
  • Sorry about that. That is true. Ignore the fact that I've written that must be a dictionary. It is not a requirement. It can be in the form of tuples. So the order is important ofcourse. – RecursionSnake Nov 26 '12 at 13:03

3 Answers3

5

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)]
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
4

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • No need for a key function in this case. – Steven Rumbalski Nov 26 '12 at 13:05
  • Great.Thanks.I was looking for the groupby function indeed. And yes it is no use for key lambda function. It works absolutely flawlessly:) – RecursionSnake Nov 26 '12 at 13:11
  • You can also use [ilen](http://funcy.readthedocs.org/en/latest/seqs.html#ilen) from [funcy](https://github.com/Suor/funcy) library instead of `len(list(...))` for speed. – Suor Jun 04 '14 at 19:46
0
python 3.2
from itertools import groupby

>>> [(i,(list(v)).count(i)) for i,v in groupby(L)]
bluish
  • 26,356
  • 27
  • 122
  • 180
raton
  • 418
  • 5
  • 14