shane
shane

Reputation: 1863

group python list of objects by 2 attributes

I have a list of objects ie

class A:
    int b
    int c

so

a = A(b=1, c=2)
b = A(b=4, c=2)
...

I have a list of these

[a, b, c, d, ..., n]

How can I sort this list into groups where in each group the objects have equality between two or more attributes of my choosing. So if I had

e = A(b=3, c=5)
h = A(b=3, c=5)

These will be grouped together into a list or some other structure (set maybe?)

Upvotes: 3

Views: 7378

Answers (1)

Lukas Graf
Lukas Graf

Reputation: 32590

Use itertools.groupby().

For example:

from itertools import groupby

class A(object):

    def __init__(self, b, c):
        self.b = b
        self.c = c


items = [A(1, 2), A(1, 2), A(1, 2), A(2, 2), A(3, 4), A(3, 4), A(5, 6)]

groups = groupby(items, lambda a: (a.b, a.c))

for key, group in groups:
    print "Key: %s, Number of items: %s" % (key, len(list(group)))

Output:

Key: (1, 2), Number of items: 3
Key: (2, 2), Number of items: 1
Key: (3, 4), Number of items: 2
Key: (5, 6), Number of items: 1

So the key function (lambda a: (a.b, a.c)) in this case is one that composes A.b and A.c into a single key (a tuple of both values).

Upvotes: 13

Related Questions