Reputation: 2227
I have a matrix of numbers in a file (distances between cities for solving TSP). I load it up into a list. After that each row in my list looks like this:
' 9999 3 5 48 48 8 8 5 5 3 3 0 3 5 8 8 5\n'
The number of whitespaces between numbers may be different on each line. Now I just want to convert it to a list of lists of ints/floats. I got that with a loop:
matrix = []
for row in lines[begin:end]:
matrix.append([float(x) for x in row.split()])
It works just fine. I am just curious if I can use a generator here (like I use it in loop), but not in loop, but in one line. I tried something like [float(x) for x in [y.split() for y in lines[begin:end]]]
, but it says:
float() argument must be a string or a number, not 'list'
So can it be solved like in one line, or should I leave it in loop?
Upvotes: 1
Views: 5612
Reputation: 15204
Of course you can.
my_list = [' 9999 3 5 48 48 8 8 5 5 3 3 0 3 5 8 8 5\n',
' 3 12 5 48 48 8 8 5 5 3 3 0 3 5 8 8 5\n']
gen = (list(map(float, f.split())) for f in my_list)
You can now iterate over gen
.
For example:
for i in gen:
print(i)
[9999.0, 3.0, 5.0, 48.0, 48.0, 8.0, ...]
[3.0, 12.0, 5.0, 48.0, 48.0, 8.0, ...]
I am assuming that by generator
you actually mean generator
by the way and not list-comprehension
. If that is not the case, the answer by @Cody is the way to go.
Upvotes: 1
Reputation: 117981
You could use the following list comprehension
matrix = [[float(i) for i in row.split()] for row in lines]
But for this particular case, it would be much faster to use numpy.genfromtxt
import numpy as np
matrix = np.genfromtxt('your_file', delimeter=' ')
Upvotes: 6