问题
Hello I am beginner in python. I have following file as "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.
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.
回答1:
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)}
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
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
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
来源:https://stackoverflow.com/questions/25879588/reading-multiple-lines-in-a-file-and-separating-their-values-at-the-same-time