Obtain the values ​​of the corresponding elements in two tables

advertisements

If a and b were lists of objects, each with a name property (e.g. a1 = A("1"), b1 = B("1"), etc.), how would I check for equivalency? I'm currently doing this:

aList = [ a1, a2, a3, a4, a5 ]
bList = [ b1, b2 ]
aNameList = []
bNameList = []

for i in aList:
    aNameList.append( i.name )
for i in bList:
    bNameList.append( i.name )

match = set(aNameList) & set(bNameList)

>>> set(['1', '2'])

But it seems kind of long and unnecessary. What is a better way to do this?


You can use list comprehensions instead to replace those temporary lists and for-loops of your example:

match = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )