0

I found a similar question here: How to group a list of tuples/objects by similar index/attribute in python? which talks about grouping a list of tuples by similar attributes. I have a list of objects; the objects have a 'day' attribute and I want to group these objects based on if they have consecutive 'day' values. e.g

input = [('a',12),('b',13)('c',15),('d',16),('e',17)]

output:

[[('a',12),('b',13)],[('c',15),('d',16),('e',17)]]
SteveMcManaman
  • 391
  • 1
  • 17

1 Answers1

1

You can do the following:

from itertools import groupby, count
from operator import itemgetter

data = [('a', 12), ('b', 13), ('c', 15), ('c', 16), ('c', 17)]


def key(i, cursor=count(0)):
    """Generate the same key for consecutive numbers"""
    return i[1] - next(cursor)


ordered = sorted(data, key=itemgetter(1))

result = [list(group) for _, group in groupby(ordered, key=key)]
print(result)

Output

[[('a', 12), ('b', 13)], [('c', 15), ('c', 16), ('c', 17)]]

The above is based on an old example found in the documentation of Python 2.6, here.

To better illustrate, what is happening, for the following example:

lst = [12, 13, 15, 16, 17]
print([v - i for i, v in enumerate(lst)])

The generated keys are:

[12, 12, 13, 13, 13]

As it can be seen, consecutive runs have the same key.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • Thank you for your answer. When I apply it to my code it throws the following error: TypeError: 'NameOfObject' object does not support indexing – SteveMcManaman Apr 17 '20 at 12:23
  • Hi, that must be because NameOfObject is not a tuple, as in your example. Instead using itemgetter, use attrgetter – Dani Mesejo Apr 17 '20 at 12:26