Using a function with multiple parameters with `map`

前端 未结 3 399
慢半拍i
慢半拍i 2021-01-18 10:57

I\'m trying to map a function that takes 2 arguments to a list:

my_func = lambda index, value: value.upper() if index % 2 else value.lower()

import string
a         


        
3条回答
  •  無奈伤痛
    2021-01-18 11:45

    map will pass each value from enumerate as a single parameter to the callback, i.e. the lambda will be called with a tuple as argument. It would be pretty surprising behaviour if map would unpack arguments which look unpackable, since then its behaviour would depend on the values it iterates over.

    To expand iterable arguments, use starmap instead, which "applies a * (star)" when passing arguments:

    from itertools import starmap
    
    n = starmap(lambda index, value: ..., enumerate(alphabet))
    

提交回复
热议问题