一种解决方案是将您的entry
列表缩减为图形字典,因为reduce(无累加器)每次查看2个相邻元素:
可以reduce
函数来实现这个功能。
from functools import reduce
graph = {}
def add_edge(u, v):
if u != 'null' and v != 'null':
if u in graph:
graph[u][v] = graph[u].get(v, 0) + 1
else:
graph[u] = {v: 1}
if v in graph:
graph[v][u] = graph[v].get(u, 0) + 1
else:
graph[v] = {u: 1}
return v
entry = ['A','B','C','null','B','A','D','null','E','F']
reduce(add_edge, entry)
print(graph)
编辑:
一种更为"纯粹"的降低方式是将相邻的元素压缩在一起,然后使用初始值进行降维:
def add_edge(graph, edges):
u, v = edges
if u != 'null' and v != 'null':
return graph
entry = ['A','B','C','null','B','A','D','null','E','F']
graph = reduce(add_edge, zip(entry[:-1], entry[1:]), {})