python map lambda实现_2个输入的python 3 map / lambda方法

在Python3中,遇到尝试使用`map`函数将字典值转换为整数但引发TypeError的问题。问题在于lambda函数期望两个参数,但实际上只接收到一个。解决方案包括使用`items()`迭代元组并解压参数,或者使用`starmap`,或者通过列表推导式直接处理字典的`values()`。这些方法都可以有效地将字典的值转换为整数。
摘要由CSDN通过智能技术生成

I have a dictionary like the following in python 3:

ss = {'a':'2', 'b','3'}

I want to convert all he values to int using map function, and I wrote something like this:

list(map(lambda key,val: int(val), ss.items())))

but the python complains:

TypeError: () missing 1 required positional argument: 'val'

My question is how can I write a lambda function with two inputs (E.g. key and val)

解决方案

ss.items() will give an iterable, which gives tuples on every iteration. In your lambda function, you have defined it to accept two parameters, but the tuple will be treated as a single argument. So there is no value to be passed to the second parameter.

You can fix it like this

print(list(map(lambda args: int(args[1]), ss.items())))

# [3, 2]

If you are ignoring the keys anyway, simply use ss.values() like this

print(list(map(int, ss.values())))

# [3, 2]

from itertools import starmap

print(list(starmap(lambda key, value: int(value), ss.items())))

# [3, 2]

I would prefer the List comprehension way

print([int(value) for value in ss.values()])

# [3, 2]

In Python 2.x, you could have done that like this

print map(lambda (key, value): int(value), ss.items())

This feature is called Tuple parameter unpacking. But this is removed in Python 3.x. Read more about it in PEP-3113

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值