In Python, I am trying to apply an operator to a two layer nested array. For example,
a = [['2.3','.2'],['-6.3','0.9']]
for j in range(2)
for i in range(2)
a[i][j] = float(a[i][j])
How can I do this without the loops? I am hoping for something akin to a= map(float,a). Of course the last script does not work for a nested list. A one line list comprehension may be acceptable too.
The first argument requires a function, and as such, you can utilize the lambda operator to map float to the sub-lists. This is an example:
Under the hood,
map
is a loop too. You should just use a list comprehension, however there is a nice way to do it with Python2 - you just need apartial
functionI don't think there is a nice way to convert this to Python3 though
With list comprehension:
One-liner with mix of
map
and listcomp:Or variants:
Choose based on your personal preference and target Python version. For large nested lists on CPython 2, the first variant is probably the fastest (if the inner lists are huge, it avoids lookup overhead to get the
float
constructor and byte code execution for the innerlist
s), and thelist
wrapped equivalent might eventually win on CPython 3; for small nested lists on all versions, the nested list comprehensions is usually going to be the fastest.