Skip to content
Advertisement

Str.format with a list to create filter

Somewhat simple question with many similar ones out there, but I cannot seem to find what I am looking for. I am trying to filter a list of images in a dbc.Carousel via an int list of location numbers. Any image title that starts with a given number will correlate to a location. So, initially, I would want all images that start with 1, 2, 3, 4, OR 5. I have:

def imageFilter(locFilter):
    
    locFilter = list(map(int, locFilter))
    #locFilter = [1, 2, 3, 4, 5]
    itemFilter = [
            {'key': k ,'src':'data:image/jpg;base64,{}'.format(v.decode())} 
                for k,v in imageEncodeDict.items() 
                # Everything works above here. .format with single numbers works too
                if k.startswith("Spot CAM {}".format(locFilter))
        ]
    return [dbc.Carousel(controls=True, indicators=True, interval=None, style=img_style, items = itemFilter)]

Unpacking the list with *locFilter DOES NOT work. How can I pass a list to work as a filter for str.format?

Advertisement

Answer

You can try using any with a generator expression:

def imageFilter(locFilter):
    
    locFilter = list(map(int, locFilter))
    #locFilter = [1, 2, 3, 4, 5]
    itemFilter = [
            {'key': k ,'src':'data:image/jpg;base64,{}'.format(v.decode())} 
                for k,v in imageEncodeDict.items() 
                if any(k.startswith("Spot CAM {}".format(f)) for f in locFilter)
        ]
    return [dbc.Carousel(controls=True, indicators=True, interval=None, style=img_style, items = itemFilter)]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement