"Map" of a nested list in Python

In Python, I'm trying to apply a statement 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 loops? I hope for something similar to a = (float, a) map. Of course, the last script does not work for a nested list. A single line understanding may also be acceptable.

+4
source share
4 answers

One slot with a combination mapand listcomp:

a = [map(float, suba) for suba in a]  # Only works on Py2

Or options:

# Both of the below work on Py2 and Py3
a = [list(map(float, suba)) for suba in a]
a = [[float(x) for x in suba] for suba in a]

Python. CPython 2 , , ( , , float list s), list CPython 3; , , , .

+5

:

a =  [[float(j) for j in i]  for i in a]
+4

, - float -. :

a = map(lambda b : map(float, b), a)
+1

map . , Python2 - partial

>>> a = [['2.3','.2'],['-6.3','0.9']]
>>> from functools import partial
>>> map(partial(map, float), a)
[[2.3, 0.2], [-6.3, 0.9]]

I don't think there is a good way to convert this to Python3, though

>>> list(map(list, map(partial(map, float), a)))  #YUKKK!
[[2.3, 0.2], [-6.3, 0.9]]
+1
source

Source: https://habr.com/ru/post/1618524/


All Articles