python 3 map/lambda method with 2 inputs

前端 未结 1 1242
谎友^
谎友^ 2021-02-05 10:01

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

相关标签:
1条回答
  • 2021-02-05 10:45

    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. You can fix it like this

      print(list(map(lambda args: int(args[1]), ss.items())))
      # [3, 2]
      
    2. If you are ignoring the keys anyway, simply use ss.values() like this

      print(list(map(int, ss.values())))
      # [3, 2]
      
    3. 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]
      
    4. 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

    0 讨论(0)
提交回复
热议问题