I am developing a dictionary Django app where Definition
s have Tag
s. I have written this generic function to collect all Tag
s from a list of Definition
s.
This is my current working version:
def get_tags(definitions):
tags = []
for d in definitions:
tags += d.tags.all()
return tags
I was trying to accomplish the same using Python's list comprehension:
tags = []
return [tags.extend(d.tags.all()) for d in definitions]
This code however does not work yet. What am I missing?
Is there an even slicker way to do this in just one line without creating the tags variable, perhaps using yield statement?
you need to iterate over all the elements d.tags.all()
, and thus need a nested list comp:
tags = [t for d in definitions for t in d.tags.all()]
this is just the list comprehension version of:
tags = []
for d in definitions:
for t in d.tags.all():
tags.append(t)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.