Can I use index information inside the map function?

前端 未结 5 1872
猫巷女王i
猫巷女王i 2020-12-28 14:40

Let\'s assume there is a list a = [1, 3, 5, 6, 8].

I want to apply some transformation on that list and I want to avoid doing it sequentially, so someth

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 15:14

    To extend Martijn Pieters' excellent answer, you could also use list comprehensions in combination with enumerate:

    >>> a = [1, 3, 5, 6, 8]
    >>> [i * v for i, v in enumerate(a)]
    [0, 3, 10, 18, 32]
    

    or

    [mapfunction(i, v) for i, v in enumerate(a)]
    

    I feel list comprehensions are often more readable than map/lambda constructs. When using a named mapping function that accepts the (i, v) tuple directly, map probably wins though.

提交回复
热议问题