开发者

using `map` to construct multiple named tuples

开发者 https://www.devze.com 2023-01-22 21:45 出处:网络
Suppose I have a namedtuple like开发者_运维知识库 >>> Point = namedtuple(\'Point\',\'x y\')

Suppose I have a namedtuple like开发者_运维知识库

>>> Point = namedtuple('Point','x y')

Why is it that I construct a single object via

>>> Point(3,4)

yet when I want to apply Point via map, I have to call

>>> map(Point._make,[(3,4),(5,6)])

I suspect this has something to do with classmethods, perhaps, and am hoping that in figuring this out I'll learn more about them as well. Thanks in advance.


Point._make takes a tuple as its sole argument. Your map call is equivalent to [Point._make((3, 4)), Point._make((5, 6))].

Using a list comprehension makes this more obvious: [Point(*t) for t in [(3, 4), (5, 6)]] achieves the same effect.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号