Search code examples
pythonlistselectziplist-comprehension

Python list comprehension with class member values


I would like to end up with a list of objects by using the member variables of two lists of such objects. So to select and combine with a condition.

Example scenario, I have class Frame, with member variable KeyFrameTime:

class Frame:
   def __init__(self):
      self.KeyFrameTime = 0.0

And now two lists with such objects

A = Frame()
A.KeyFrameTime = 1.0
B = Frame()
B.KeyFrameTime = 2.0
FooList = [A, B]

C = Frame()
C.KeyFrameTime = 2.0
D = Frame()
D.KeyFrameTime = 3.0
BarList = [C, D]

And with these lists FooList and BarList, I would like to use some condition and select the objects that fulfill those values. For example if the condition would be KeyFrameTime equality, I would get the wanted list with:

resultList = []
for f in FooList:
   for b in BarList:
      if(f.KeyFrameTime == b.keyFrameTime):
         resultList.append(f)

This gives me desired resultList, however, I am wondering if zip/map/filter or list comprehension somehow to end up with same result.


Solution

  • Use itertools.product() and a list comprehension:

    import itertools
    
    resultList = [f for f, b in itertools.product(FooList, BarList) if f.KeyFrameTime == b.KeyFrameTime]