How do I make Maps and lambdas work with a matrix in python 3.4?

前端 未结 5 1980
有刺的猬
有刺的猬 2020-12-20 07:58

I often avoid me to write posts like this but I\'m new in python 3.4 and I need a help with this code.

Suppose we have the following list:

v = [ [ x,         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 08:37

    You can do:

    >>> list(map(lambda x: ''.join(map(str, x)), v))
    ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']
    

    This executes the function lambda x: ''.join(map(str, x)) for each element in v. An element in v is a list with one string and one integer as values. This means x, as received by the lambda function, is a list with those two values.

    We then need to ensure all values in that list are strings before passing them to join(). This means we'll call map(str, x) to turn all values in the sublist x into strings (['a', 1] becomes ['a', '1']). We can then join them by passing the result of that to ''.join(...) (['a', '1'] becomes ['a1']). This is done for each list in v so this gives us the desired result.

    The result of map is a so-called mapobject in Python 3.x so we wrapped everything in a list() call to end up with a list.

    Also, a list comprehension is arguably more readable here:

    >>> [x[0] + str(x[1]) for x in v]
    ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4']
    

提交回复
热议问题