读取文件中的多行,并同时分离它们的值,以将其存储在字典中 [英] Reading multiple lines in a file, and separating their values at the same time, to store it in dictionary

查看:32
本文介绍了读取文件中的多行,并同时分离它们的值,以将其存储在字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我是python的初学者.我有以下文件作为"test.txt"

Hello I am beginner in python. I have following file as "test.txt"

1 2 5
2 6 7

as so on .....

我想读取值并将其存储到字典中我想出了以下代码,但无法正常工作作为 [x.split('')for edge中的x.readline().rstrip().split('')] 只能访问文件的一行.同样,它返回不能应用int()类型转换的列表.它可以循环访问多行,但我想知道使用pythonic的方式.

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. Also this returns list on which int() typecasting can't be applied. It can access multiple line in a loop but I would like to know pythonic way to do this.

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.

推荐答案

这是一个很干净的dict理解,如果有点长的话:

Here's a dict comprehension that's pretty clean, if a bit long:

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

请注意使用生成器表达式遍历文件中的行,而不是使用列表补全-(f中的行的map(int,line.split())) vs [f中的行的map(int,line.split()).这样一来,我们就不必将所有文件内容都存储在内存中,如果文件很大,这一点就很重要.

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]. 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 用于将 line.split()返回的所有字符串转换为整数.我认为在这里使用 map 比等效的列表理解要好: [int(x)in line.split()中的x).

map is used to convert all the strings returned by line.split() to integers. I think using map here is nicer than the equivalent list comprehension: [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

要真正等于dict理解,我们需要创建一个生成器函数来遍历文件:

To be truly equivalent with the dict comprehension, we'd need to create a generator function for iterating over the file:

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

这篇关于读取文件中的多行,并同时分离它们的值,以将其存储在字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆