You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中解包列表内的元组以用于map函数?

解决方案
  • 使用lambda配合map拆包元组:
    不用修改原函数,通过lambda把每个元组拆成两个参数传给func:

    def func(a,b):
        return a+b
    
    num = [(0,4),(6,3),(2,2),(9,1)]
    result = map(lambda t: func(*t), num)
    # 转成列表查看结果
    print(list(result))  # 输出 [4, 9, 4, 10]
    
  • 使用functools.starmap(更简洁):
    starmap专门处理这类“可迭代对象元素为参数组”的场景,会自动把每个元组的元素作为独立参数传入目标函数:

    from functools import starmap
    
    def func(a,b):
        return a+b
    
    num = [(0,4),(6,3),(2,2),(9,1)]
    result = starmap(func, num)
    print(list(result))  # 输出 [4, 9, 4, 10]
    

补充说明:你提到的JavaScript式参数解构写法def func((a,b)):是Python 2的语法,Python 3已经移除了,上面两种方式是适配当前Python版本的简洁实现。

内容的提问来源于stack exchange,提问作者rafiki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:37:06