python - __init__() 缺少 1 个必需的位置参数:'b'
问题描述
这是两个向量:
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = [3, 4, 5, 6, 7, 8, 9, 10]
假设我这样定义Test
类:
class Test:
def __init__(self, a, b):
self.a = a
self.b = b
当我执行命令list(map(Test, zip(a,b)))
时,它说__init__() missing 1 required positional argument: 'b'
。我知道如果我有t = (1,2)
,那么我可以创建一个Test
with的实例inst = Test(*t)
。我可以申请*
解决我的问题map
吗?有解决方法吗?
解决方案
是的。你可以这样做:
tests = list(map(lambda args: Test(*args), zip(a,b)))
它将zip
值作为 lambda 的参数并在调用时解开它们Test()
这几乎是什么itertools.starmap
- 所以这是另一种选择:
tests = list(starmap(Test, zip(a,b)))
更好的选择是使用列表理解,这使得代码更具可读性:
tests = [Test(arg_a, arg_b) for (arg_a,arg_b) in zip(a, b)]
推荐阅读
- python - groupby 条件均值
- reactjs - 找不到模块'@material-ui/core'
- unity3d - 想知道 SpriteRenderer.color 有多贵,因为我打算用它来为我屏幕上的所有精灵着色?
- c++ - 如何使用 Windows 10、64 位解决 Matlab R2018b 中的 C++ MEX 文件编译错误?
- sql-server - SQL Server docker 无法使用撰写配置在 Docker Mac 桌面上启动
- python - 贝叶斯网络:与 R 相比,Python 中的结构学习非常慢
- database - 项目正在运行但数据库连接未找到
- r - 在 X 轴上创建列标题的折线图
- c# - 为什么我的并行任务代码不能达到 100% 的 CPU 利用率?
- c++ - 我可以在没有 Xcode 的 Mac 上使用 UnrealEngine 和 C++