每個人!
我目前正在執行以下任務:
“撰寫一個函式,該函式將從 pajek .net 檔案中讀取資料并將其保存到字典中。”
“pajek.net”檔案中寫入的資料為:
*Vertices 5
1 "x"
2 "y"
3 "z"
4 "m"
5 "n"
*Arcs
1 2 3
1 3 5
2 3 4
2 5 2
3 4 1
4 5 3
我寫的函式是這樣的:
def read(pajek):
list1 = []
vertices = []
arcs = []
edges = []
with open(pajek, 'r') as file:
lines = file.readlines()
isStar = ""
for line in lines:
if "*" in line:
isStar = line #in other files I'm working on, there is only a "*" in some lines
elif isStar.find("*Vertices") != -1:
vertices.append(line.split())
elif isStar.find("*Arcs") != -1:
arcs.append(line.split())
elif isStar.find("*Edges") != -1:
edges.append(line.split())
return vertices, arcs, edges
下一部分(“...將其保存到字典中。”)給我帶來了麻煩。
我試過了,但總是有一些錯誤......
有人可以幫我弄這個嗎?
另外,我不能使用匯入和模塊!
PS
我是 Python 新手,因此我仍在學習 Python 特定的技巧和竅門
編輯:串列 => 串列 1
uj5u.com熱心網友回復:
在您的主要添加此代碼以從 read 函式的輸出創建一個字典:
vertices, arcs, edges = read("pajek.net")
result = {"vertices": vertices,"arcs": arcs,"edges": edges}
print(result)
結果會是這樣:
{
"vertices":[
[
"1",
"x"
],
],
"arcs":[
[
"1",
"2",
"3"
],
],
"edges":[
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377173.html
上一篇:將字典結構解壓為嵌套字典
