Reputation: 533
As title, I have been trying to read text from file, convert to int
and store it in a list. My text file look like this:
1,2
3,4
5,6
I want to read this file, put each pair of numbers into a list m
, and store those lists in a bigger list lis
. Here is my attempt:
def read_file():
lis = []
m = [0,0]
with open("data.txt") as f:
for line in f:
m[0], m[1] = line.split(",") # assign to list m
m[0] = int(m[0]) # cut off '\n' and for later use
m[1] = int(m[1])
lis.append(m) # store in lis
print lis
I expect the lis
to be like this:
[[1, 2], [3, 4], [5, 6]]
But instead, it is:
[[5, 6], [5, 6], [5, 6]]
I have tried insert
instead of append
but it seems like that's not where it has problems. I need some help - thank you in advance!
Upvotes: 1
Views: 133
Reputation: 1673
In lis
all index reference to one list m
. If any update in m
is takes place, m
is update every where
Try this
lis.append( list(map(int,line.split(","))))
Output
[['1', '2'], ['3', '4'], ['5', '6']]
Upvotes: 2
Reputation: 92854
Use csv.reader
object instead which uses ,
(comma) as default field separator:
import csv
with open('data.txt') as f:
reader = csv.reader(f)
result = [list(map(int, lst)) for lst in reader]
print(result)
The output:
[[1, 2], [3, 4], [5, 6]]
https://docs.python.org/3/library/csv.html?highlight=csv#csv.reader
Upvotes: 1
Reputation: 82889
You are reusing the same list m
in each iteration of the loop, each time overwriting the values set in the previous iteration. In the end, lis
holds many references to the same list.
Instead, assign a new value to m
as a whole in the loop:
for line in f:
m = [0,0]
m[0], m[1] = line.split(",")
m[0] = int(m[0])
m[1] = int(m[1])
lis.append(m)
Or shorter:
for line in f:
m = line.split(",")
m[0] = int(m[0])
m[1] = int(m[1])
lis.append(m)
Or even shorter, using map:
for line in f:
m = list(map(int, line.split(",")))
lis.append(m)
Or even more shorter, using a list comprehension:
lis = [list(map(int, line.split(","))) for line in f]
Upvotes: 4
Reputation: 82755
def read_file():
lis = []
with open("data.txt") as f:
for line in f:
m, n = line.split(",")
lis.append([int(m), int(n)])
print lis
Upvotes: 2