简体   繁体   English

读取文件中的多行,并同时分隔其值,以将其存储在字典中

[英]Reading multiple lines in a file, and separating their values at the same time, to store it in dictionary

Hello I am beginner in python. 您好,我是python的初学者。 I have following file as "test.txt" 我有以下文件作为“ test.txt”

1 2 5
2 6 7

as so on .....

I want to read the values and store it to a dictionary I have come up with following code but its not working as [x.split(' ') for x in edges.readline().rstrip().split(' ')] can access only one line of the file. 我想读取这些值并将其存储到字典中,但我想出了以下代码,但[x.split(' ') for x in edges.readline().rstrip().split(' ')]只能访问文件的一行。 Also this returns list on which int() typecasting can't be applied. 同样,这将返回无法应用int()类型转换的列表。 It can access multiple line in a loop but I would like to know pythonic way to do this. 它可以循环访问多行,但我想知道pythonic的方法。

connection = {(int(source),int(dest)):int(weight) for source,dest,weight in [x.split(' ') for x in edges.readline().rstrip().split(' ')]}

Can you please suggest the correct method to read this kind of file and then store it in a dictionary. 您能否建议正确的方法来读取此类文件,然后将其存储在词典中。 Thanks. 谢谢。

Here's a dict comprehension that's pretty clean, if a bit long: 这是一个很干净的dict理解,如果有点长的话:

with open("test.txt") as f:
  connection = {(a, b) : c for a,b,c in (map(int, line.split()) for line in f)}

Note the use of a generator expression to iterate over the lines in the file instead of a list compherension - (map(int, line.split()) for line in f) vs [map(int, line.split()) for line in f] . 请注意,使用生成器表达式来遍历文件中的行,而不是使用列表补全- (map(int, line.split()) for line in f)[map(int, line.split()) for line in f] This allows us to avoid having to store all of the files content in memory, which can be important if the file is large. 这使我们避免必须将所有文件内容存储在内存中,如果文件很大,这可能很重要。

map is used to convert all the strings returned by line.split() to integers. map用于将line.split()返回的所有字符串转换为整数。 I think using map here is nicer than the equivalent list comprehension: [int(x) for x in line.split()] . 我认为在这里使用map比等效的列表理解要好: [int(x) for x in line.split()]

Here's the same logic broken up into its individual parts: 这是分解成各个部分的相同逻辑:

connection = {}
with open("test.txt") as f:
    for line in f:
        a,b,c = map(int, line.split())
        connection[(a,b)] = c

To be truly equivalent with the dict comprehension, we'd need to create a generator function for iterating over the file: 为了与dict理解真正等效,我们需要创建一个生成器函数来迭代文件:

def f_it(f):
    for line in f:
        yield map(int, line.split())

connection = {}
with open("test.txt") as f:
    for a,b,c in f_it(f):
        connection[(a,b)] = c

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

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