Set operations on object attributes question

A.T.Hofkamp hat at se-162.se.wtb.tue.nl
Tue Oct 23 15:52:46 CEST 2007


On 2007-10-23, TheSeeker <duane.kaufman at gmail.com> wrote:
> Hi,
>
> I have run into something I would like to do, but am not sure how to
> code it up. I would like to perform 'set-like' operations (union,
> intersection, etc) on a set of objects, but have the set operations
> based on an attribute of the object, rather than the whole object.
>
> For instance, say I have (pseudo-code):
>
> LoTuples1 = [(1,1,0),(1,2,1),(1,3,3)]
> Set1=set(LoTuples1)
> LoTuples2 = [(2,1,3),(2,2,4),(2,3,2)]
> Set2=set(LoTuples2)
>
> What I would like to be able to do is:
>
> Set3 = Set1union(Set2)
> Set3.intersection(Set2, <use object[2]>)
>
> to return:
> set([(2,1,3), (1,3,3)])
>
> How can one do this operation?

Put your data in a class, and implement __hash__ and __eq__
Finally, put your objects in sets.

Albert




More information about the Python-list mailing list