简体   繁体   English

Python 列表理解 Django 对象

[英]Python list comprehension Django objects

I am developing a dictionary Django app where Definition s have Tag s.我正在开发字典 Django 应用程序,其中Definition s 具有Tag s。 I have written this generic function to collect all Tag s from a list of Definition s.我编写了这个通用的 function 来从Definition列表中收集所有Tag

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:我试图使用 Python 的列表理解来完成同样的事情:

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?是否有一种更巧妙的方法可以在不创建标签变量的情况下仅在一行中执行此操作,也许使用 yield 语句?

you need to iterate over all the elements d.tags.all() , and thus need a nested list comp:您需要遍历所有元素d.tags.all() ,因此需要一个嵌套列表 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM