如何在不使用 shell 的情况下打印出生成器对象?

how can i print out the generator object without using the shell?

在网上看到这个例子,它是一个 dfs 函数,可以找到一个图中的所有循环。

我正在尝试将循环部分添加到函数中,这样我就不必使用 shell 来获取结果。 我是生成器对象的新手,所以我不确定如何显示周期。

版本使用 shell:

def dfs(graph, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
        if path and state == end:
            yield path
            continue
    for next_state in graph[state]:
        if next_state in path:
            continue
        fringe.append((next_state, path+[next_state]))

>>> graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }
>>> cycles = [[node]+path  for node in graph for path in dfs(graph, node, node)]
>>> len(cycles)
7
>>> cycles
[[1, 5, 2, 1], [1, 3, 1], [1, 2, 1], [2, 1, 5, 2], [2, 1, 2], [3, 1, 3], [5, 2, 1, 5]]

这是我的尝试:

def dfs(g, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
        if path and state == end:
            yield path
            continue
    for next_state in g[state]:
        if next_state in path:
            continue
        fringe.append((next_state, path+[next_state]))
    cycles = (list([node]+path for node in g for path in dfs(g, node, node)))
    print("cycles",cycles)
return path

dfs(graph, 1, 1)

尝试了几个不同的开始和结束节点,结果都是一样的。

我的图和上面一样,

 graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] }

输出= 生成器对象 dfs 位于 0x000001D9CB846EB8

有什么想法吗?

首先,请修正你的缩进。

我认为你的问题是缺少 [] 列表理解的结果。

尝试换行 cycles = (list([node]+path for node in g for path in dfs(g, node, node)))cycles = [[node]+path for node in g for path in dfs(g, node, node)]

这是您要找的吗?

def dfs(g, start, end):
    fringe = [(start, [])]
    while fringe:
        state, path = fringe.pop()
        if path and state == end:

            yield path
            continue
        for next_state in g[state]:
            if next_state in path:
                continue
            fringe.append((next_state, path+[next_state]))


graph = {1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2]}
cycles = [[node]+path for node in graph for path in dfs(graph, node, node)]
print(cycles)

您不需要在生成器中使用 return,因此您可以使用列表理解或常规循环遍历它。