![](/img/trans.png)
[英]How to read and store values from a text file into a dictionary. [python]
[英]Python: Read tree like data from text file and store in dictionary
我有一個文本文件,其中包含樹狀數據,數據之間用空格分隔,結構如下:'分支數''節點名稱'... 0(0表示沒有其他分支)例如:
1 A 3 B 2 C 0
D 0
E 1 F 0
G 2 H 0
I 0
相應的字典“樹”應類似於:
tree = {'A': {'B': {'C': {},
'D': {}},
'E': {'F': {}},
'G': {'H': {},
'I': {}}}}
我認為遞歸方法是正確的方法,但是我無法使其起作用。 到目前為止,我具有以下功能:
def constructNodes(branch):
global nodes_temp
if not branch:
branch = deque(file.readline().strip().split())
node1 = branch.popleft()
nodes_temp.add(node1)
nbBranches = int(branch.popleft())
for i in xrange(nbBranches):
constructNodes(branch)
return nodes_temp
先謝謝您的幫助。
您不需要雙端隊列來遍歷序列,可以使用常規的python可迭代。 這可以使事情更加簡潔。
data = """
1 A 3 B 2 C 0
D 0
E 1 F 0
G 2 H 0
I 0"""
def construct_nodes(data):
return dict((next(data), construct_nodes(data))
for _ in xrange(int(next(data))))
print construct_nodes(iter(data.split()))
我認為這是您想要的:
from collections import deque
data = deque('''\
1 A 3 B 2 C 0
D 0
E 1 F 0
G 2 H 0
I 0'''.split())
def constructNodes():
D = {}
count = int(data.popleft())
for _ in range(count):
node = data.popleft()
D[node] = constructNodes()
return D
tree = constructNodes()
print(tree)
輸出:
{'A': {'B': {'C': {}, 'D': {}}, 'G': {'H': {}, 'I': {}}, 'E': {'F': {}}}}
使用某些格式:
{'A': {'B': {'C': {},
'D': {}},
'G': {'H': {},
'I': {}},
'E': {'F': {}}}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.