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

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)
主站蜘蛛池模板: 台江县| 漯河市| 思茅市| 湖州市| 乐陵市| 松潘县| 定日县| 久治县| 收藏| 洞口县| 凤阳县| 肇州县| 泰兴市| 浦县| 孟州市| 涪陵区| 延津县| 五大连池市| 池州市| 松阳县| 漳浦县| 龙山县| 安多县| 大姚县| 慈溪市| 墨玉县| 满洲里市| 新宁县| 宜阳县| 绥棱县| 凤庆县| 偏关县| 静宁县| 平罗县| 象山县| 古交市| 岳阳市| 英吉沙县| 遵义市| 柏乡县| 射洪县|