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

前端 未结 5 1971
有刺的猬
有刺的猬 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:30

    I agree with Mike that map(lambda is silly. In this case, '{}{}'.format pretty much does the job your lambda is supposed to do, so you can use that instead:

    starmap('{}{}'.format, v)
    

    That uses itertools.starmap. If you want to use map, you can do it like this:

    map('{}{}'.format, *zip(*v))
    

    But really I'd just do

    (c + str(n) for c, n in v)
    

    Edit: A comparison of map+lambda vs generator expression, showing that the latter is shorter, clearer, more flexible (unpacking), and faster:

    >>> from timeit import timeit
    
    >>> r = range(10000000)
    >>> timeit(lambda: sum(map(lambda xy: xy[0]+xy[1], zip(r, r))), number=1)
    7.221420832748007
    >>> timeit(lambda: sum(x+y for x, y in zip(r, r)), number=1)
    5.192609298897533
    
    >>> timeit(lambda: sum(map(lambda x: 2*x, r)), number=1)
    5.870139625224283
    >>> timeit(lambda: sum(2*x for x in r), number=1)
    4.4056527464802
    
    >>> r = range(10)
    >>> timeit(lambda: sum(map(lambda xy: xy[0]+xy[1], zip(r, r))), number=1000000)
    7.047922363577214
    >>> timeit(lambda: sum(x+y for x, y in zip(r, r)), number=1000000)
    4.78059718055448
    

提交回复
热议问题