使用`map`构造多个命名元组

Ric*_*ick 4 python

假设我有一个像这样的名字

>>> Point = namedtuple('Point','x y')
Run Code Online (Sandbox Code Playgroud)

为什么我通过构造单个对象

>>> Point(3,4)
Run Code Online (Sandbox Code Playgroud)

但是当我想通过地图应用Point时,我必须打电话

>>> map(Point._make,[(3,4),(5,6)])
Run Code Online (Sandbox Code Playgroud)

我怀疑这可能与类方法有关,我希望在搞清楚这一点时我也会更多地了解它们.提前致谢.

hab*_*bit 7

Point._make以元组为唯一参数.你的map电话相当于[Point._make((3, 4)), Point._make((5, 6))].

使用列表理解使这更加明显:[Point(*t) for t in [(3, 4), (5, 6)]]实现相同的效果.

  • 你也可以使用itertools中的starmap - list(starmap(Point,[[1,2],[3,4]])) (4认同)