制作这个pythonic

Moh*_*hit 0 python

如何制作以下剪辑代码"pythonic"

 tag_list = []
 for d in docs:
        tags = d["tags"]
        for tag in tags:
            if tag not in tag_list:
                tag_list.append(tag)
Run Code Online (Sandbox Code Playgroud)

Cat*_*lus 10

在3.x(可能是2.7,我不记得了),你可以做一套理解:

tag_list = {tag for doc in docs for tag in doc["tags"]}
Run Code Online (Sandbox Code Playgroud)

在2.x中,您可以从生成器表达式构建集合:

tag_list = set(tag for doc in docs for tag in doc["tags"])
Run Code Online (Sandbox Code Playgroud)

在那之后,如果你真的需要它作为一个列表,那就做list(tag_list).


Hug*_*ell 6

taglist = set()
for d in docs:
    taglist |= set(d["tags"])
taglist = list(taglist)
Run Code Online (Sandbox Code Playgroud)

要么

from itertools import chain
taglist = list(set(chain(*(d["tags"] for d in docs))))
Run Code Online (Sandbox Code Playgroud)

或者(thx到@ lazy1):

from itertools import chain
taglist = list(set(chain.from_iterable(d["tags"] for d in docs)))
Run Code Online (Sandbox Code Playgroud)

要么

import operator
taglist = list(reduce(operator.or_, (set(d["tags"]) for d in docs)))
Run Code Online (Sandbox Code Playgroud)