简体   繁体   English

Python - 从文本文件到字典的邻接列表

[英]Python - adjacency list from text file into a dictionary

With networkx i am able to generate a text file which represents an adjacency list of a graph.使用networkx,我可以生成一个代表图形邻接列表的文本文件。 I need to convert the text file into a dictionary.我需要将文本文件转换成字典。 So the key is the left most number on each line, and it is a list of values for the rest of the numbers to the right on the line.所以关键是每行最左边的数字,它是该行右边数字的 rest 的值列表。 The value list can sometimes be empty.值列表有时可能为空。 We can call the input file test.txt.我们可以调用输入文件test.txt。 Thanks!谢谢!

For example, this is what im looking for: {1: [], 2: [3,7], 3: [4,7,9], 4: [7,9], 9: []}例如,这就是我要查找的内容:{1: [], 2: [3,7], 3: [4,7,9], 4: [7,9], 9: []}

This is the text file generated to be converted:这是生成的要转换的文本文件:

#adjlist.py
# GMT Tue May 26 14:48:55 2020
# 
1
2 3 7
3 4 7 9
4 7 9
7 9
9

Reading a text file is trivial with the open() function.使用open() function 读取文本文件很简单。 I suggest using the .read() method rather than iterating over the open file to read lines as reading the file in bulk into memory is much faster than iterating over the lines from the file on disk.我建议使用.read()方法而不是遍历打开的文件来读取行,因为将文件批量读取到 memory 比从磁盘上的文件中遍历行快得多。 That is of course if the file is smaller than your RAM.当然,如果文件小于您的 RAM。 .strip() returns a copy of the string with leading and trailing characters remove. .strip()返回删除前导和尾随字符的字符串副本。 .split() splits with the delimiter given, here we use \n to split the file to lines. .split()使用给定的分隔符拆分,这里我们使用\n将文件拆分为行。

Finally, we iterate over each line and call .split() on the line, this time splitting by space.最后,我们遍历每一行并在该行上调用.split() ,这次按空格分割。 This returns a list of items, where the [0] indexed item will be your key and the rest ( [1:] ) will be your values.这将返回一个项目列表,其中[0]索引项目将是您的键,而 rest ( [1:] ) 将是您的值。

You can use a defaultdict from the collections built-in library to achieve multiple items to a single dictionary key.您可以使用collections内置库中的defaultdict来实现单个字典键的多个项目。

from collections import defaultdict

with open("test.txt") as f:
    lines = f.read().strip().split("\n")

d = defaultdict(list)

for line in lines:
    ls = line.split(" ")
    d[ls[0]] = ls[1:]

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

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