namedtuple:
namedtuple类位于collections模块,有了namedtuple后通过属性访问数据能够让我们的代码更加的直观更好维护。
namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数据,能够迭代,还能够方便的通过属性名来访问数据。
collections module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set
, and tuple
.
collections.
namedtuple
(typename, field_names[, verbose=False][, rename=False])
Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__()
method which lists the tuple contents in a name=value
format.
The field_names are a sequence of strings such as ['x', 'y']
. Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example 'x y'
or 'x, y'
.
Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword
such as class, for, return, global, pass, print, or raise.
If rename is true, invalid fieldnames are automatically replaced with positional names. For example, ['abc', 'def', 'ghi', 'abc']
is converted to ['abc', '_1', 'ghi', '_3']
, eliminating the keyword def
and the duplicate fieldname abc
.
If verbose is true, the class definition is printed just before being built.
Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.
New in version 2.6.
Changed in version 2.7: added support for rename.