带有3个输入的python 3 map/lambda方法 [英] python 3 map/lambda method with 2 inputs

查看:147
本文介绍了带有3个输入的python 3 map/lambda方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 3中有如下字典:

I have a dictionary like the following in python 3:

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

我想使用map函数将他的所有值转换为int,我写了这样的东西:

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

但是python抱怨:

but the python complains:

TypeError:()缺少1个必需的位置参数:'val'

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

我的问题是如何编写具有两个输入(例如key和val)的lambda函数

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

推荐答案

ss.items()将给出一个可迭代的对象,该对象将在每次迭代时提供元组.在lambda函数中,已将其定义为接受两个参数,但是元组将被视为单个参数.因此,没有值可以传递给第二个参数.

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.

  1. 您可以像这样修复它

  1. You can fix it like this

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

  • 如果仍然忽略键,只需使用ss.values()这样

    print(list(map(int, ss.values())))
    # [3, 2]
    

  • 否则,按照Ashwini的建议, Chaudhary ,使用 itertools.starmap

  • Otherwise, as suggested by Ashwini Chaudhary, using itertools.starmap,

    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]
    

  • 在Python 2.x中,您可以这样做

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

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

    此功能称为元组参数解包.但这已在Python 3.x中删除.在 PEP-3113

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

    这篇关于带有3个输入的python 3 map/lambda方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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