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!
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]
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.