递归生成器和`yield from`

时间:2017-02-02 12:11:32

标签: python python-3.x

我有一个数据结构,它基本上是嵌套列表/字典的混合:

class System:
    def __init__(self, name, subsystems, uri):
        self.name = name
        self.subsystems = subsystems
        self.uri = uri

A = System("A", [], "http://A")
B1 = System("B1", [], "http://B/B1")
B21 = System("B12", [], "http://B/B2/B21")
B22 = System("B22", [], "http://B/B2/B22")
B2 = System("B2", [B21, B22], "http://B/B2")
B = System("B", [B1, B2], "http://B")
C1 = System("C1", [], "http://C/C1")
C = System("C", [C1], "http://C")
S = System("S", [A, B, C], None)

在Python中,我编写了以下递归生成器:

def find_subsystem(system, name):
    if system.name == name:
        yield system.uri
    for sub in system.subsystems:
        yield from find_subsystem(sub, name)

允许我像

那样进行“查询”
next(find_subsystem(S, "B22"))
#=> 'http://B/B2/B21'

list(find_subsystem(S, "B22"))
#=> ['http://B/B2/B21', 'http://B/B2/B22']

这是“最佳”(性能和/或代码清洁度)吗?

0 个答案:

没有答案