2017-04-18 91 views
0

我试图通过读取.txt文件以这种格式在Python中创建一个邻接表的字典:如何阅读txt文件,并创建邻接表Python字典

1 2 
1 3 
1 10 
2 3 
4 5 
4 6 
4 10 
5 6 
7 8 
7 9 
7 10 
8 9 

我想要得到的解释是

adjacency_list_dict = {[1]:{[2,3,10],[2]:这个格式的[1,3],...}等

注意的是,尽管看上去像一个定向图中,它实际上是无向的,并且字典中每个键的列表值必须包含所有相邻节点例如[10]:[1,4,7]尽管10不在任何txt文件行的第一列。

现在我坚持这个代码块:

# Main file for assignment 2 
input_filename = "example_graph_1.txt" 
def create_teams(): 
    return [] 
def create_lex(): 
    return {} 
def make_to_list(node): 
    return [node] 

teams = create_teams() 
adjacency_graph = create_lex() 

with open(input_filename) as graph_input: 
    for line in graph_input: 
     nodes = [int(x) for x in line.split()] 
     for i in nodes: 
      if make_to_list(i) not in teams: 
       teams.append(make_to_list(i)) 
      if i not in adjacency_graph: 
       adjacency_graph[i] = create_teams() 
    print adjacency_graph 
    print teams 

请忽略所有其他变量,字典adjacency_graph是我很关心。 :)

我应该如何进行?

+0

你有一些代码可以显示吗? – Astrom

+0

将其分解成更小的部分。首先打开文件并打印每一行。然后从那里出发。 –

+0

@Astrom heloo,请再看看,我编辑的帖子,我希望它可以帮助:) – Marios

回答

3

您可以通过使用.setdefault和拆分来完成此操作。基本上,如果未定义,代码将在密钥parts[0]上创建一个新列表。之后,我们追加到列表中。

di = {} 

with open("file.txt", "r") as fi: 
    for line in fi: 
     parts = line.split() 
     di.setdefault(parts[0],[]).append(parts[1]) 

print(di) 

并使其双向的最简单方法是附加字典两种方式:

di = {} 

with open("file.txt", "r") as fi: 
    for line in fi: 
     parts = line.split() 
     di.setdefault(parts[0],[]).append(parts[1]) 
     di.setdefault(parts[1],[]).append(parts[0]) 

print(di) 
+0

就像那样! – Astrom

+0

@Jammeth_Q感谢您的输入,我更新了答案。 – Neil

1
import numpy 

l1, l2 = numpy.genfromtxt('t.txt', dtype='float').T 
uniques = list(numpy.unique(l1))+list(numpy.unique(l2))  
dic = {} 

for i in numpy.unique(uniques): 
    a =list(l2[numpy.where(l1 == i)[0]]) 
    b =list(l1[numpy.where(l2 == i)[0]]) 

    c = list(numpy.unique(a+b)) 
    dic[i] = c 

输出: {1.0:[2.0,3.0,10.0],2.0:[ 1.0,0.0,3.0] 3.0:[1.0,2.0],4.0:[5.0,6.0,10.0],5.0:[4.0,6.0],6.0:[4.0,5.0],7.0:[8.0,9.0,10.0],8.0 :[7.0,9.0],9.0:[7.0,8.0],10.0:[1.0,4.0,7.0]}