通过`map`使用带有多个参数的函数 [英] Using a function with multiple parameters with `map`

查看:223
本文介绍了通过`map`使用带有多个参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个带有2个参数的函数映射到列表中:

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
alphabet = string.ascii_lowercase

n = map(my_func, enumerate(alphabet))
for element in n:
    print(element)

这给了我TypeError: <lambda>() missing 1 required positional argument: 'value'.

将我的lambda映射到此输入的正确方法是什么?

What is the correct way to map my lambda onto this input?

推荐答案

Python无法自动解压缩lambda参数. enumerate返回一个tuple,因此lambda必须将该元组作为唯一参数

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

您需要:

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

现在考虑map + lambda +手动拆包的丑陋之处,我建议改用其他生成器理解:

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))

(由于您的输入已经是小写字母,因此我删除了lower()调用)

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

这篇关于通过`map`使用带有多个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆