[Tutor] create numpy array from list of strings
Kent Johnson
kent37 at tds.net
Wed Jun 4 12:34:16 CEST 2008
On Tue, Jun 3, 2008 at 10:35 PM, washakie <washakie at gmail.com> wrote:
> I guess I assumed there would be a way to 'nest' list
> comprehension somehow.
Sure, just nest them. You have:
tempDATA=[]
for i in data[stind:-1]:
tempDATA.append([float(j) for j in i.split()])
This has the form
tempDATA=[]
for i in sequence:
tempDATA.append(expr(i))
Code in this form can become the list comprehension
tempDATA = [ expr(i) for i in sequence ]
which in your case becomes
tempDATA=[ [float(j) for j in i.split()] for i in data[stind:-1] ]
You can also have multiple loops in a single list comp; if you wanted
a single list of floats, instead of a list of lists, you could write
tempDATA=[ float(j) for i in data[stind:-1] for j in i.split() ]
Note that the order of 'for' clauses is reversed; it is the same order
as you would use with nested for loops.
Kent
More information about the Tutor
mailing list