简体   繁体   English

生成器Python的返回列表

[英]Return list from generator Python

I'm trying to make a customize version for DFS from the original version of networkx. 我正在尝试从networkx的原始版本制作DFS的自定义版本。 You can relate to the original version of DFS from networkx here: networkx DFS 您可以在此处从networkx 关联DFS的原始版本: networkx DFS

In my implementation, I want to add a child which contain "if" in the label to a list and return the list after all but I can't make it 在我的实现中,我想将标签中包含“ if”的子项添加到列表中,并毕竟返回列表,但我无法做到

def extract_expression(label):
    m = re.search('if(.+?)goto', label)
    if m:
       return m.group(1)
    return None

def dfs_edges(G, source=None):  
    path = list()
    if source is None:
        nodes = G
    else:
        nodes = [source]
    visited=set()
    for start in nodes:
        if start in visited:
            continue
        visited.add(start)
        stack = [(start,iter(G[start]))]
        while stack:
            parent,children = stack[-1]
            try:
                child = next(children)
                label = G.node[child]['label']
                if "if" in label:
                    print child
                    # print extract_expression(label)
                exp = extract_expression(label)
                path.append(exp)
                if child not in visited:
                    yield parent,child      
                    visited.add(child)
                    stack.append((child,iter(G[child])))
            except StopIteration:
                stack.pop()
    return path

Throw the error 抛出错误

    return path
SyntaxError: 'return' with argument inside generator

A generator function must always yield its result. 生成器函数必须始终产生其结果。

You could simply replace the return path with yield path but that would be bad practice and overall inconsistent. 您可以简单地将return path替换为yield path但这将是一种不好的做法,并且总体上是不一致的。 You'd return the parent, child and at one time suddenly get a list. 您将返回parent, child并突然获得一份清单。

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

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