Using a function with multiple parameters with `map`

前端 未结 3 372
慢半拍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:25

    Python cannot unpack lambda parameters automatically. enumerate returns a tuple, so lambda has to take that tuple as sole argument

    You need:

    n = map(lambda t: t[1].upper() if t[0] % 2 else t[1], enumerate(alphabet))
    

    Considering now the ugliness of map + lambda + manual unpacking, I'd advise the alternate generator comprehension instead:

    n = (value.upper() if index % 2 else value for index,value in enumerate(alphabet))
    

    (I removed the lower() call since your input is already lowercase)

提交回复
热议问题