Andrew A
Andrew A

Reputation: 13

Intersection of Object Attributes in Python

So I made 2 sets of objects, like such.

class 4digits:
    def __init__(self, value):
        self.value = value
        self.first = (value - (value % 100)) / 100
        self.last = value % 100

These are all 4 digits objects, so it would be like...

object.value = 1234
object.first = 12
object.last = 34

if I had 2 sets, set1 and set2, I'd like to update set1 and set2 to only contain the objects where set1 has a last attribute that matches to set2's first attribute.

Such as... 1234 in set1 will match to 3456 in set 2.

I could do this as a list instead of a set pretty easily but a set feels a lot more efficient if I could figure out the procedure, but not sure how I can return an intersection of object's attributes. Any help.

Edited: Because I was asked for code, and my hypothetical wasn't exactly what I was actually doing.

Thanks to Jez I got this answer:

def lastinfirst(list1, list2):
    firsts = set( l2.first for l2 in list2)
    newlist1 = [ l1 for l1 in list1 if l1.last in firsts]
    return newlist1

def firstinlast(list1, list2):
    lasts = set( l1.last for l1 in list1)
    newlist2 = [ l2 for l2 in list2 if l2.first in lasts]
    return newlist2

Upvotes: 1

Views: 1840

Answers (1)

jez
jez

Reputation: 15349

If I've understood correctly what you want, this should do it:

# Get the set of unique boroughs in which people want rooms:
wantedboroughs = set( w.borough for w in wantrooms )

# Get all records for people who have rooms in those boroughs:
result = [ h for h in haverooms if h.borough in wantedboroughs ]

Well, now you've edited your question to not be about rooms and boroughs at all. But maybe you can generalize the principles exemplified here.

Upvotes: 3

Related Questions