简体   繁体   English

python语法中的namedtuple来自内置类型和orderedDict

[英]namedtuple in python syntax weird from built-in types and orderedDict

this is my first question on stackoverflow. 这是我关于stackoverflow的第一个问题。 I just learnt the namedtuple and found sth weird. 我刚学会了这个名字,发现很奇怪。

When you want to initiate a namedtuple from an iterable, you have to either add a prefix * or use the _make method. 如果要从iterable启动namedtuple,则必须添加前缀*或使用_make方法。

for instance: 例如:

City=namedtuple('city',['name','country','population','coordinates'])

delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))

delhi = City(*('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889)))

But when you initiate a tuple, dict or even orderedDict from the same collection package, you can just tuple() or dict() or orderedDict(). 但是当你从同一个集合包中启动一个元组,dict甚至orderedDict时,你可以只使用tuple()或dict()或orderedDict()。

for instance: 例如:

from collections import OrderedDict

items = (
('A', 1),
('B', 2),
('C', 3)
)

regular_dict = dict(items)

ordered_dict = OrderedDict(items)

Why the syntax for namedtuple is so weird? 为什么namedtuple的语法如此奇怪? Thanks! 谢谢!

You can see some discussion here about why namedtuple was designed this way. 你可以在这里看到有关为什么以这种方式设计namedtuple的讨论。 The basic reason is that the "normal" way to create a namedtuple is with a call like MyTupleClass(1, 2, 3) , where the values are accepted as separate arguments. 基本原因是创建一个MyTupleClass(1, 2, 3)的“正常”方式是使用类似MyTupleClass(1, 2, 3)的调用,其中值被接受为单独的参数。 If it accepted only one iterable argument (as tuple does), you would have to write MyTupleClass((1, 2, 3)) with an extra set of parentheses (that is, MyTupleClass(1, 2, 3) would raise an error, as tuple(1, 2, 3) does). 如果它只接受一个可迭代的参数(如tuple那样),则必须使用一组额外的括号来编写MyTupleClass((1, 2, 3)) (也就是说, MyTupleClass(1, 2, 3)会引发错误,如tuple(1, 2, 3)所做的那样)。 It is true that this means you have to use an extra star (or use the ._make() method) if initializing from an iterable, but this isn't any harder, it's just different. 确实,这意味着如果从迭代中初始化,你必须使用额外的星(或使用._make()方法),但这不是更难,它只是不同。 The decision was apparently to make the simple case (initializing with literal values) easier, at the expense of making a more complex case (unpacking from an iterable) a bit different from a regular tuple. 这个决定显然是为了使简单的情况(用文字值初始化)更容易,代价是使一个更复杂的情况(从迭代中解包)与常规元组略有不同。

From your example, it behaves similarly to a dict: 从您的示例中,它的行为类似于dict:

from collections import namedtuple
MyTuple = namedtuple('MyTuple', 'A B C')

items = (('A', 1), ('B', 2), ('C', 3))

my_tuple = MyTuple(**dict(items))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM