[英]Stripping string from lines in text file and reading columns into dictionary with lists as values
I've been struggling a bit with getting my input file into the right format for my algorithm. 我一直在努力将输入文件转换为适合算法的正确格式。
I want to read this text file: 我想阅读这个文本文件:
1 -> 7,8
11 -> 1,19
219 -> 1,9,8
Into this dictionary: 进入这本字典:
{ 1: [7, 8], 11: [1, 19], 219: [1, 9, 8]}
I've tried this code: 我已经试过这段代码:
with open("file.txt", "r+") as f:
f.write(f.read().replace("->", " "))
f.close()
d = {}
with open("file.txt") as file:
for line in file:
(key, val) = line.split()
d[key] = val
But with this code it get's stuck on the fact that there are more than 2 arguments in the second column. 但是有了这段代码,它就陷入了一个事实,即第二列中有两个以上的参数。 How can make a list out of the elements in the second column and use that list as the value for each key?
如何才能从第二列的元素中列出一个列表,并将该列表用作每个键的值?
There is no need to do that pre-processing step to remove the '->'
. 无需执行该预处理步骤即可删除
'->'
。 Simply use: 只需使用:
d = {}
with open("file.txt") as file:
for line in file:
left,right = line.split('->')
d[int(left)] = [int(v) for v in right.split(',')]
You can even use dictionary comprehension and make it a one-liner: 您甚至可以使用字典理解并将其变成单行:
with open("file.txt") as file:
d = {int(left) : [int(v) for v in right.split(',')]
for left,right in (line.split('->') for line in file)
}
This gives: 这给出:
>>> d
{1: [7, 8], 11: [1, 19], 219: [1, 9, 8]}
Nest a generator expression with str.split
in a dictionary comprehension, converting the key to an integer and mapping the value to integers: 将带有
str.split
的生成器表达式str.split
在字典理解中,将键转换为整数并将值映射为整数:
with open('file.txt') as f:
result = {int(k):list(map(int, v.split(','))) for k,v in (line.split(' -> ') for line in f)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.