[NCLUG] help w/ python list comprehension
Stephen Warren
swarren at wwwdotorg.org
Tue Aug 20 20:53:36 MDT 2013
On 08/20/2013 07:55 PM, Michael Cullerton wrote:
> 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]
The fact you can use "in" on item.tags here ...
> for tag in filter_tags:
> if not tag in item_tags:
... implies you can do so directly there too, and hence avoid even
creating the item_tags variable. In other words, replace that last list
with:
if not tag in item.tags:
> has_tags = False
And you may as well add the following here:
break
>
> if has_tags: items_by_tag.append(item)
>
> return items_by_tag
If you really want to use a list comprehension, e.g. for the sake of
learning them, then perhaps:
items_by_tag = []
for item in items:
missing = [tag for tag in filter_tags and not tag in item.tags]
if not missing:
items_by_tag.append(item)
(note: I hope that list comprehension syntax is correct; I never use
them because they're often considered a little confusing and
unnecessary; just open-coding the loop is a bit more obvious)
More information about the NCLUG
mailing list