首页 > 解决方案 > __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),那么我可以创建一个Testwith的实例inst = Test(*t)。我可以申请*解决我的问题map吗?有解决方法吗?

标签: python

解决方案


是的。你可以这样做:

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

推荐阅读