I have this nested list:
JavaScript
x
2
1
l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]
2
I want to convert each element in l
to float
. I have this code:
JavaScript
1
5
1
newList = []
2
for x in l:
3
for y in x:
4
newList.append(float(y))
5
How can I solve the problem with a nested list comprehension instead?
See also: How can I get a flat result from a list comprehension instead of a nested list?
Advertisement
Answer
Here is how you would do this with a nested list comprehension:
JavaScript
1
2
1
[[float(y) for y in x] for x in l]
2
This would give you a list of lists, similar to what you started with except with floats instead of strings.
If you want one flat list, then you would use
JavaScript
1
2
1
[float(y) for x in l for y in x]
2
Note the loop order – for x in l
comes first in this one.