我有以下形式的資料:
A=B=11
A=C=6
A=D=5
B=C=19
B=D=17
C=D=6
但我想把它轉換成這種格式:
graph= [[ 0, 10, 15, 20 ],
[ 10, 0, 35, 25 ],
[ 15, 35, 0, 30 ],
[ 20, 25, 30, 0 ]]
這是如何實作的?我知道多維陣列是如何作業的,但是使用 python 構造這個矩陣非常令人困惑
uj5u.com熱心網友回復:
您可以使用字典來制作鄰接串列。然后列舉該字典的鍵以定義每個鍵的索引。然后最后將權重復制到最終的矩陣結構中:
nodes = {}
for line in open("input.txt").read().splitlines():
a, b, weight = line.split("=")
nodes.setdefault(a, []).append((b, int(weight)))
nodes.setdefault(b, []).append((a, int(weight)))
n = len(nodes)
key2index = { key: i for i, key in enumerate(nodes.keys()) }
graph = [[0] * n for _ in range(n)]
for a, edges in nodes.items():
row = graph[key2index[a]]
for b, weight in edges:
row[key2index[b]] = weight
print(graph)
矩陣中的零表示沒有邊,就像您的示例在矩陣的主對角線上的情況一樣(即您的示例圖沒有“回圈”)。
評論
正如您在已洗掉的評論中要求跳過檔案的第一行,這里是適用于執行此操作的代碼:
nodes = {}
lines = open("input.txt").read().splitlines()
for line in lines[1:]:
a, b, weight = line.split("=")
nodes.setdefault(a, []).append((b, int(weight)))
nodes.setdefault(b, []).append((a, int(weight)))
n = len(nodes)
key2index = { key: i for i, key in enumerate(nodes.keys()) }
graph = [[0] * n for _ in range(n)]
for a, edges in nodes.items():
row = graph[key2index[a]]
for b, weight in edges:
row[key2index[b]] = weight
print(graph)
uj5u.com熱心網友回復:
你可以這樣做:
import pandas as pd
import numpy as np
# Change to your filename.
filename = 'graph.csv'
# Lines to skip.
skip_rows = 1
# Whether the graph is undirected.
undirected = True
# Read file and convert vertex names to integer indices. Names are sorted.
# I.e., A=0, B=1, etc. (like in your example).
df = pd.read_csv(filename, sep='=', header=None, names=['n1', 'n2', 'weight'], skiprows=skip_rows)
cat_type = pd.CategoricalDtype(categories=sorted(np.unique(np.concatenate((df['n1'].unique(), df['n2'].unique())))), ordered=True)
df['n1'] = df['n1'].astype(cat_type).cat.codes
df['n2'] = df['n2'].astype(cat_type).cat.codes
n_nodes = len(cat_type.categories)
graph = np.full((n_nodes, n_nodes), np.nan)
for n1, n2, w in zip(df['n1'], df['n2'], df['weight']):
graph[n1, n2] = w
if undirected:
graph[n2, n1] = w
np.fill_diagonal(graph, 0)
print(graph)
[[ 0. 11. 6. 5.]
[11. 0. 19. 17.]
[ 6. 19. 0. 6.]
[ 5. 17. 6. 0.]]
如果,則表示根據您的檔案,從節點到節點graph[i, j] == NaN沒有邊(長度為 1 的路徑) 。ij
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/475524.html
上一篇:列印此RandomQuickSort執行的步數。Java代碼
下一篇:batch批處理筆記
