How should you read a 2D integer array?
Question:
I’m new to python. I would like to read a 2D integer array from a text file, one row per line in the file, the numbers separated by commas. This works:
s = f.read()
ss = s.splitlines()
mx = []
for i in range(0,len(ss)):
mx.append([])
for s1 in ss[i].split(','):
mx[i].append(int(s1))
Is there a simpler way to do this?
Answers:
Use a nested list comprehension:
with open(filename) as f:
mx = [[int(x) for x in line.split(',')] for line in f]
or list comprehension with map
:
mx = [map(int, line.split(',')) for line in f]
Note that in Python 3 you’ll need an extra list()
call around map
.
If NumPy is available:
>>> import numpy as np
>>> mx = np.loadtxt(filename, delimiter=',', dtype=int).tolist()
There is a built-in module for reading comma-separated files (csv
):
import csv
mx = [map(int, row) for row in csv.reader(open(filename))]
Also, if you are planning to do math with this array, you might find it useful to install and use numpy
:
import numpy
mx = numpy.loadtxt(filename, delimiter=',', dtype=int)
mx
will now be an array
rather than a list of lists.
I’m new to python. I would like to read a 2D integer array from a text file, one row per line in the file, the numbers separated by commas. This works:
s = f.read()
ss = s.splitlines()
mx = []
for i in range(0,len(ss)):
mx.append([])
for s1 in ss[i].split(','):
mx[i].append(int(s1))
Is there a simpler way to do this?
Use a nested list comprehension:
with open(filename) as f:
mx = [[int(x) for x in line.split(',')] for line in f]
or list comprehension with map
:
mx = [map(int, line.split(',')) for line in f]
Note that in Python 3 you’ll need an extra list()
call around map
.
If NumPy is available:
>>> import numpy as np
>>> mx = np.loadtxt(filename, delimiter=',', dtype=int).tolist()
There is a built-in module for reading comma-separated files (csv
):
import csv
mx = [map(int, row) for row in csv.reader(open(filename))]
Also, if you are planning to do math with this array, you might find it useful to install and use numpy
:
import numpy
mx = numpy.loadtxt(filename, delimiter=',', dtype=int)
mx
will now be an array
rather than a list of lists.