[英]Detecting a Cycle in a Directed Graph Python
我正在嘗試從看起來像這樣的文本文件中提取有向圖(1:是節點,第二個數字是鄰居,然后是權重、鄰居、權重等:
1: 2 3 4 5 6 2
2: 3 -4
3: 8 4
4: 5 6
5: 4 -3 8 8
6: 7 3
7: 6 -6 8 7
8:
下面是我的代碼:
fileName = ("graphin_Fig1.txt")
dictionary = {} # allocate dictionary space
with open(fileName,'r') as file: # open file
for line in file: # read each line of the file
tokens = line.strip().split(' ') # separate each number, remove white space
node = int (tokens[0].split(':')[0]) # remove :, separate node from neighbors and weights
pos = 1 # initialize counter
listtups = [] # allocate array to hold neghbors and weights
while pos < len(tokens): # while end of line has not been reached
listtups.append((int(tokens[pos]), int (tokens[pos++1]))) # add ints to array
pos += 2 # counter
if len(listtups) > 0: # if neigbors and edges are detected
dictionary[node] = listtups # add to nodes
print (dictionary)
這是 output:
`{1: [(2, 3), (4, 5), (6, 2)], 2: [(3, -4)], 3: [(8, 4)], 4: [(5, 6)], 5: [(4, -3), (8, 8)], 6: [(7, 3)], 7: [(6, -6), (8, 7)]}`
我正在嘗試將我的字典用於其他算法,但只有當字典看起來像下面的示例時它們才會起作用:
dictionary = {
1: {2: 3, 4: 5, 6: 2},
2: {3: -4},
3: {8: 4},
4: {5: 6},
5: {4: -3, 8: 8},
6: {7: 3},
7: {6: -6, 8: 7},
8: {}
}
我是 python 的新手,真的很掙扎。 如何更改我的代碼以使我提取的字典看起來像上面的示例?
你很親密。 剩下的唯一事情就是將您的元組列表轉換為字典,而不是:
dictionary[node] = listtups # add to nodes
嘗試
dictionary[node] = dict(listtups)
並刪除檢查鄰居長度的if
語句,因為您的示例顯示即使沒有相鄰節點,您也希望添加節點。
好吧,您根本沒有相同的數據結構。 你想要的是一個包含字典的字典。 例如:
outer_d = {"inner_d":{...}, ...}
你正在做的是一個字典,每個鍵的值不是字典,而是一個列表(元組),例如:
outer_d = {"key":[...], ... }
你明白其中的區別嗎?
fileName = ("graphin_Fig1.txt")
dictionary = {}
with open(fileName,'r') as file:
for line in file:
tokens = line.strip().split(' ')
node = int (tokens[0].split(':')[0])
pos = 1 # initialize counter
listtups = {} # another dictionnary, not a list!
while pos < len(tokens):
listtups[int(tokens[pos])] = int(tokens[pos++1])
pos += 2 # counter
if len(listtups) > 0:
dictionary[node] = listtups
print (dictionary)
產生:
{1: {2: 3, 4: 5, 6: 2}, 2: {3: -4}, 3: {8: 4}, 4: {5: 6}, 5: {4: -3, 8: 8}, 6: {7: 3}, 7: {6: -6, 8: 7}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.