我有一個這樣的行串列:
Lines = ['1', '2', '3', '4', '5', '6', '7', '8']
每條線有兩個點 I 和 J:
LinesDetail = {
'1': {
'I': '100',
'J': '101'},
'2': {
'I': '101',
'J': '102'},
'3': {
'I': '256',
'J': '257'},
'4': {
'I': '257',
'J': '258'},
'5': {
'I': '258',
'J': '259'},
'6': {
'I': '304',
'J': '305'},
'7': {
'I': '305',
'J': '306'},
'8': {
'I': '102',
'J': '103'}}
正如您在圖片中看到的,其中一些線具有相互點,因此它們相互連接,我需要知道哪些線相互連接。
我嘗試了while回圈,但我不知道如何解決這類問題。

結果將是:
result = [["1","2","8"],["3","4","5"],["6","7"]]
所有線條都是垂直的
uj5u.com熱心網友回復:
這是一個尋找連通分量的圖問題。一種可能的解釋是外部鍵是標簽,內部字典是邊緣(內部字典值是節點)。如果依賴性不是問題,Python 有一個很好的 APInetworkx可以處理圖形。具體來說,可以使用 UnionFind 資料結構來查找不相交的子集。
from networkx.utils.union_find import UnionFind
# reverse the label-edge mapping to get a mapping from nodes to edge labels
edges = {}
for k, d in LinesDetail.items():
for v in d.values():
edges.setdefault(v, []).append(k)
# construct union-find data structure
c = UnionFind()
for lst in edges.values():
c.union(*lst)
# get the disjoint sets as sorted lists
result = list(map(sorted, c.to_sets()))
result
# [['1', '2', '8'], ['3', '4', '5'], ['6', '7']]
uj5u.com熱心網友回復:
不是最優化的解決方案,但自從我研究它以來就把它放在那里
LinesDetail = {
'1': {
'I': '100',
'J': '101'},
'2': {
'I': '101',
'J': '102'},
'3': {
'I': '256',
'J': '257'},
'4': {
'I': '257',
'J': '258'},
'5': {
'I': '258',
'J': '259'},
'6': {
'I': '304',
'J': '305'},
'7': {
'I': '305',
'J': '306'},
'8': {
'I': '102',
'J': '103'}}
Lines = ['1', '2', '3', '4', '5', '6', '7', '8']
results = []
for item in Lines:
match_this = LinesDetail[item]['J']
list_form = []
for key, value in LinesDetail.items():
if match_this == value['I']:
results.append([item, key])
needed_list = []
for i in range(0, len(results)-1):
if results[i][1] == results[i 1][0]:
yes_list = results[i][:1] results[i 1]
needed_list.append(yes_list)
else:
try:
if results[i][1] == results[i 2][0]:
continue
except:
needed_list.append(results[i 1])
print(needed_list)
輸出:
[['1', '2', '8'], ['3', '4', '5'], ['6', '7']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/491208.html
上一篇:找不到滿足要求的版本評估
