Set operations on object attributes question

TheSeeker duane.kaufman at gmail.com
Tue Oct 23 13:45:34 EDT 2007


Hi,

Thanks for the response! (See below for more discussion)

On Oct 23, 10:39 am, Raymond Hettinger <pyt... at rcn.com> wrote:
> [Duane]
>
> > 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?
>
> Conceptually, there is more than one operation going on. First,
> finding the attributes shared in both sets:
>    ca = set(t[2] for t in LoTuples1) & set(t[2] for t in LoTuples2)
> which gives:
>    set([3])

In my use case, I already know object[2] is the key I wish to use, so
I could do this without the first step.
I am thinking of object[n] as the 'key' I wish to operate on, and the
other items in the tuple are useful attributes
I'll need in the end.

>
> Second, find any tuple which has that attribute (including multiple
> results for the same attribute):
>    set(t for t in (LoTuples1 + LoTuples2) if t[2] in ca)
> which returns:
>    set([(2, 1, 3), (1, 3, 3)])
>
> Wanting multiple results for the same attribute value (i.e. both
> (2,1,3) and (1,3,3) have 3 in the second position) is why multiple
> steps are needed; otherwise, the behavior of intersection() is to
> return a single representative of the equivalence class.
>
This second operation is really much like what I cam up with before I
started looking into exploiting the power of sets
(this same operation can be done strictly with lists, right?)

Since what I _really_ wanted from this was the intersection of the
objects (based on attribute 2), I was looking for a set-based
solution,
kinda like a decorate - <set operation> - undecorate pattern. Perhaps
the problem does not fall into that category.

Thanks for your help,
Duane




More information about the Python-list mailing list