“Map” a nested list in Python

后端 未结 4 884
自闭症患者
自闭症患者 2021-02-14 05:07

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 r         


        
相关标签:
4条回答
  • 2021-02-14 05:26

    One-liner with mix of map and listcomp:

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

    Or variants:

    # 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]
    

    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 inner lists), and the list 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.

    0 讨论(0)
  • 2021-02-14 05:32

    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:

    a = map(lambda b : map(float, b), a)
    
    0 讨论(0)
  • 2021-02-14 05:33

    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 a partial function

    >>> 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 nice way to convert this to Python3 though

    >>> list(map(list, map(partial(map, float), a)))  #YUKKK!
    [[2.3, 0.2], [-6.3, 0.9]]
    
    0 讨论(0)
  • 2021-02-14 05:42

    With list comprehension:

    a =  [[float(j) for j in i]  for i in a]
    
    0 讨论(0)
提交回复
热议问题