Using a function with multiple parameters with `map`

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

    Python can't unpack lambda parameters automatically.

    But you can get round this by passing an extra range argument to map:

    import string
    
    alphabet = string.ascii_lowercase
    
    n = map(lambda i, v: v.upper() if i % 2 else v.lower(),
            range(len(alphabet)),
            alphabet)
    
    for element in n:
        print(element)
    

    As per the docs:

    map(function, iterable, ...)

    Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see itertools.starmap().

提交回复
热议问题