python - Group objects with an identical list attribute -
i have 2 classes:
class a: def __init__(self, name, li): self.b_list = li class b: def __init__(self, i): self.i =
class a
contains list of objects of type class b
.
assuming have list of class a
objects, how can group class a
objects have identical b_list
together?
for example:
a_list = [] li = [b(1), b(2), b(3)] a_list.append(a(li)) li = [b(2), b(3)] a_list.append(a(li)) li = [b(1), b(2), b(3)] a_list.append(a(li))
after processing should give 2 lists, 1 list first , third a
, , list second a
. or in nutshell:
result = [ [ a([b(1),b(2),b(3)]), a([b(1),b(2),b(3)]) ], [ a([b(2),b(3)] ] ]
for starters, i've removed name
parameter class a, since rest of details omitted it.
to group class objects together, you're going need define meant when 2 objects equal. i've created __cmp__
method let sort on objects comparing them.
now, since objects composed of b objects, you're going need define meant 2 b objects being equal. i've created __eq__
method in class b that.
next, i've sorted instances make grouping them easier, , added __str__
method class a, , __repr__
method class b can verify being grouped correctly.
i haven't added error checking anywhere, code little fragile.
class a: def __init__(self, li): self.b_list = li def __cmp__(self, other): return cmp([elem.i elem in self.b_list], [elem.i elem in other.b_list]) def __str__(self): return "a({})".format(self.b_list) class b: def __init__(self, i): self.i = def __eq__(self, other): return self.i == other.i def __repr__(self): return "b({})".format(self.i) def main(): a_list = [] li = [b(1), b(2), b(3)] a_list.append(a(li)) li = [b(2), b(3)] a_list.append(a(li)) li = [b(1), b(2), b(3)] a_list.append(a(li)) result = [] last_item = none item in sorted(a_list): if last_item , item == last_item: result[-1] = result[-1] + [item] else: result.append([item]) last_item = item row in result: print [str(elem) elem in row] if __name__ == '__main__': main()
result:
['a([b(1), b(2), b(3)])', 'a([b(1), b(2), b(3)])'] ['a([b(2), b(3)])']
Comments
Post a Comment