A = ['node1', 'node2', 'node3', 'node4', 'node5'] #nodes
B = {'node1':'node2', 'node3':'node4', 'node4':'node5'} #connections
C = [['node1', 'node2'], ['node3', 'node4', 'node5']] #wanted result
我希望所有節點都相互連接;當輸入為 A、B 時,我想要 C。
def demo(A, B):
# code
return C
我嘗試了復雜的方法來獲得想要的結果,但沒有成功。我希望有人能幫助我解決這個問題。
uj5u.com熱心網友回復:
試試這個代碼
只需回圈到字典中并將鍵值對轉換為串列
并將它們合并在一個單獨的回圈中
代碼:
B1 = {'node1':'node2', 'node3':'node4', 'node4':'node5'}
B2 = {'node1':'node2', 'node3':'node4', 'node4':'node5', 'node5':'node6'}
def nodes_to_list(_dict):
res = sorted([[i, j] for i, j in _dict.items()])
for index1, i in enumerate(res):
for index2, j in enumerate(res):
if index1 != index2:
if any(a in j for a in i):
res[index1] = sorted(set(i j))
del res[index2]
return res
print(nodes_to_list(B1))
print(nodes_to_list(B2))
輸出:
[['node1', 'node2'], ['node3', 'node4', 'node5']]
[['node1', 'node2'], ['node3', 'node4', 'node5', 'node6']]
告訴我它是否不起作用...
uj5u.com熱心網友回復:
networkx 是一個選項:
import networkx as nx
# Initialize graph
G = nx.Graph()
# Put all your nodes into graph
G.add_nodes_from(A)
# Add edges to graph
for n1, n2 in B.items():
G.add_edge(n1, n2)
# Create list of connected components of G
C = [list(c) for c in nx.connected_components(G)]
uj5u.com熱心網友回復:
您可以使用遞回生成器函式:
nodes = {'node1':'node2', 'node3':'node4', 'node4':'node5'}
def paths(n=None, c = []):
if n is None:
for a in nodes:
if all(j != a for j in nodes.values()):
yield from paths(a)
elif n not in nodes:
yield c [n]
else:
yield from paths(nodes[n], c [n])
print(list(paths()))
輸出:
[['node1', 'node2'], ['node3', 'node4', 'node5']]
在更大的節點字典上:
nodes = {'node1':'node2', 'node3':'node4', 'node4':'node5', 'node5':'node6' }
輸出:
[['node1', 'node2'], ['node3', 'node4', 'node5', 'node6']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/375455.html
上一篇:計算好節點的數量
