我将其表示为一个简单的edge:edge
字典:
links = {
0: [1],
1: [2, 4],
2: [3],
4: [5],
3: [1]
}
然后你可以迭代它:
def get_all_paths(links, length, start=0):
paths = [[start]]
for i in range(length):
newpaths = []
for path in paths:
try:
for next_node in links[path[-1]]:
newpaths.append(path + [next_node])
except KeyError:
pass
paths = newpaths
return paths
get_all_paths(links, 3)
#>>> [[0, 1, 2, 3], [0, 1, 4, 5]]
每个[0, 1, 2, 3]
到的转换[(0,1), (1,2), (2,3)]
可以在单独的步骤中完成。
它也适用于您的图表:
links = {'L0': {'L1': '01'}, 'L1': {'L2': '12', 'L4': '14'}, 'L2': {'L3': '23'}, 'L3': {'L1': '31'}, 'L4': {'L5': '45'}}
def get_all_paths(links, length, start=0):
paths = [[start]]
for i in range(length):
newpaths = []
for path in paths:
try:
for next_node in links[path[-1]]:
newpaths.append(path + [next_node])
except KeyError:
pass
paths = newpaths
return paths
get_all_paths(links, 3, start='L0')
#>>> [['L0', 'L1', 'L4', 'L5'], ['L0', 'L1', 'L2', 'L3']]
然后,您可以将每个路径转换为['01', '14', '45']
表单。
由于您似乎想知道如何进行最后一次转换,这里有一个方法:
paths = [['L0', 'L1', 'L4', 'L5'], ['L0', 'L1', 'L2', 'L3']]
def join_paths(paths, links):
for path in paths:
yield [links[a][b] for a, b in zip(path, path[1:])]
list(join_paths(paths, links))
#>>> [['01', '14', '45'], ['01', '12', '23']]
zip(path, path[1:])
将转向[1, 2, 3, 4]
变成[(1, 2), (2, 3), (3, 4)]
.
这for a, b in
获取每一对并设置a
和b
到其中的项目。
这links[a][b]
将从字典中查找路径名。
yield
一次返回每个项目,因此您必须调用list
的输出join_paths
才能将其放入列表中。