[英]How to turn a txt file into a hashmap of arrays
I'm trying to take a text file with the format like this:我正在尝试获取格式如下的文本文件:
4
0 2 3 4
1 1 3 4
2 1 2 4
3 1 2 3
and parse it into something like this:并将其解析为如下内容:
G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]}
Where the first line is the number of lines and the first digit of every subsequent line is the order the array is in the hashmap.其中第一行是行数,随后每一行的第一个数字是数组在 hashmap 中的顺序。
data = """4
0 2 3 4
1 1 3 4
2 1 2 4
3 1 2 3""".splitlines()[1:]
# or
# with open("file.txt") as fp:
# data = fp.readlines()[1:]
G = {i + 1: list(map(int, line.split()[1:])) for i, line in enumerate(data)}
print(G)
{1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2, 4], 4: [1, 2, 3]}
This is the general idea:这是一般的想法:
reader = open("INSERT FILE")
numLines = int(reader.readline().strip())
dict = {}
for line in reader:
key = int(line[0])
values = line[2:].split()
values = [int(value) for value in values]
dict[key+1] = values
print(dict)
Output: Output:
{1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2, 4], 4: [1, 2, 3]}
One line solution, using dictionary comprehension:一行解决方案,使用字典理解:
{index:list(map(int, line.split(" ")[1:])) for index, line in enumerate(open(FILE_NAME).readlines()) if index != 0}
Edit: Explanation编辑:解释
open(FILE_NAME).readlines()
- Returns each line in the file as a string open(FILE_NAME).readlines()
- 将文件中的每一行作为字符串返回list(map(int, line.split(" ")[1:]))
- Split each line by space, ignore the first element and convert the rest into int. list(map(int, line.split(" ")[1:]))
- 按空格拆分每一行,忽略第一个元素并将 rest 转换为 int。 Finally, you get a list of int.index != 0
to ignore the first line since it's of no use for us index != 0
忽略第一行,因为它对我们没有用 I'm trying to take a text file with the format like this:我正在尝试使用如下格式的文本文件:
4
0 2 3 4
1 1 3 4
2 1 2 4
3 1 2 3
and parse it into something like this:并将其解析为如下内容:
G = {1:[2,3,4], 2:[1,3,4], 3:[1,2,4], 4:[1,2,3]}
Where the first line is the number of lines and the first digit of every subsequent line is the order the array is in the hashmap.其中第一行是行数,每个后续行的第一个数字是数组在 hashmap 中的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.