官术网_书友最值得收藏!

Named tuples

The namedtuple method returns a tuple-like object that has fields accessible with named indexes as well as the integer indexes of normal tuples. This allows for code that is, to a certain extent, self-documenting and more readable. It can be especially useful in an application where there is a large number of tuples and we need to easily keep track of what each tuple represents. The namedtuple inherits methods from tuple and it is backward-compatible with tuple.

The field names are passed to the namedtuple method as comma and/or whitespace separated values. They can also be passed as a sequence of strings. Field names are single strings and they can be any legal Python identifier that does not begin with a digit or an underscore. A typical example is shown here:

The namedtuple method take two optional Boolean arguments, verbose and rename. When verbose is set to True then the class definition is printed when it is built. This argument is depreciated in favor of using the __source attribute. When the rename argument is set to True then any invalid field names will be automatically replaced with positional arguments. As an example, we attempt to use def as a field name. This would normally generate an error, but since we have assigned rename to True, the Python interpreter allows this. However, when we attempt to look up the def value, we get a syntax error, since def is a reserved keyword. The illegal field name has been replaced by a field name created by adding an underscore to the positional value:

In addition to the inherited tuple methods, the named tuple also defines three methods of its own, _make() , asdict(), and _replace. These methods begin with an underscore to prevent potential conflicts with field names. The _make() method takes an iterable as an argument and turns it into a named tuple object, for example:

The _asdict method returns an OrderedDict with the field names mapped to index keys and the values mapped to the dictionary values, for example:

The _replace method returns a new instance of the tuple, replacing the specified values, for example:

In[82]:  sl._replace(x=7, z=9)
Out[82]: space2 (x=7, _l=4, z=9)
主站蜘蛛池模板: 将乐县| 平乐县| 侯马市| 德钦县| 长春市| 开封县| 建始县| 巴青县| 夏津县| 阳高县| 林周县| 塔河县| 安图县| 临潭县| 资阳市| 河南省| 石台县| 丰城市| 西藏| 合作市| 扬中市| 清苑县| 揭东县| 扎兰屯市| 江永县| 科技| 宣城市| 抚州市| 临武县| 泾阳县| 库尔勒市| 西华县| 安岳县| 永德县| 偏关县| 丹阳市| 栖霞市| 渝中区| 浮梁县| 婺源县| 南通市|