8

I have a list like

x = [2, 2, 1, 1, 1, 1, 1, 1]

I would like to put the repeated numbers together like

[[2,2],[1,1,1,1,1,1]] 
agf
  • 171,228
  • 44
  • 289
  • 238
graph
  • 389
  • 2
  • 5
  • 10

1 Answers1

27
[list(g) for k, g in itertools.groupby(iterable)]

This is exactly what itertools.groupby is for.

If you want nonconsecutive numbers grouped, like in the comment by @Michal,

[list(g) for k, g in itertools.groupby(sorted(iterable))]
agf
  • 171,228
  • 44
  • 289
  • 238
  • Nice trick. What would this solution work for? I mean iterables of ints, floats, strings I guess it's ok. How about iterables of your own class objects ? Would these work if __eq__ or __hash__ is implemented ? – Bogdan Aug 11 '11 at 12:27
  • 1
    So long as they compare equal it will work; code equivalent to the implementation is at the link in my answer. So, just implement `__eq__` (and also `__hash__` because objects that are equal need to hash the same) and it will work. – agf Aug 11 '11 at 12:30
  • 3
    You don't need `__hash__` just for this code to work, but it's a good idea to implement it so that your objects can be used effectively in dicts and sets. – Ned Batchelder Aug 11 '11 at 12:38