[NCLUG] help w/ python list comprehension

Michael Cullerton michaelc at cullerton.com
Tue Aug 20 19:55:03 MDT 2013


Hey Folks,

This is a bit off topic, but hopefully it's an opportunity (for me) to learn.

I have the following python code. Is there a way to clean up the chunk inside the "for item in items" loop?

Mike


# items is a list of items 
# filter_tags is a list of tags used to filter the items

# if an item has all the filter_tags, append it to items_by_tag

items_by_tag = []

for item in items:
    has_tags = True
    item_tags = [tag for tag in item.tags]
    for tag in filter_tags:
        if not tag in item_tags:
            has_tags = False

    if has_tags: items_by_tag.append(item)

return items_by_tag



More information about the NCLUG mailing list