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

Python中lambda多位置参数报错及代码优化咨询

问题:如何在map中解构列表参数为多个位置变量?

给定以下列表:

arr = [1, 5, 2, 6, 3, 7, 4]
cmds = [[1, 3, 2], [3, 5, 1], [2, 7, 4]]

针对cmds中的每个命令,需要得到:

[arr[1:3][2], arr[3:5][1], arr[2:7][4]]

已尝试可行代码:

list(map(lambda x: arr[x[0]:x[1]][x[2]], cmds))

希望写出更简洁的代码,想用3个位置参数i、j、k替代单独的x,尝试写法触发TypeError:

list(map(lambda i, j, k: arr[i:j][k], cmds)) # 触发TypeError

解决方案

原因分析

报错是因为map会将cmds中的每个子列表作为单个参数传递给lambda,但你定义的lambda需要3个位置参数,参数数量不匹配,因此触发TypeError。

方法1:使用itertools.starmap

itertools.starmap的作用是将每个可迭代元素解包为多个参数传递给目标函数,正好满足需求:

from itertools import starmap

arr = [1, 5, 2, 6, 3, 7, 4]
cmds = [[1, 3, 2], [3, 5, 1], [2, 7, 4]]

result = list(starmap(lambda i, j, k: arr[i:j][k], cmds))
print(result)  # 输出: [2, 3, 6]

方法2:在lambda内部手动解包

如果不想引入额外模块,可以在lambda内部手动将子列表解包为三个参数:

# 写法1:嵌套lambda解包
result = list(map(lambda x: (lambda i,j,k: arr[i:j][k])(*x), cmds))

# 写法2:Python 3.8+ 用海象运算符解构
result = list(map(lambda x: arr[i:j][k] if (i,j,k) := x else None, cmds))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:20:52