繁体   English   中英

如何使用邻接表python阅读txt文件并创建字典

[英]How to read txt file and create dictionary with adjacency list 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。 :)

我应该如何进行?

您可以使用.setdefault和split来执行此操作。 基本上,如果未定义,代码将在关键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)
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,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]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM