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

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)
主站蜘蛛池模板: 勐海县| 连江县| 宁国市| 林甸县| 天津市| 同江市| 汪清县| 马关县| 宝兴县| 工布江达县| 原阳县| 北流市| 额济纳旗| 南开区| 雅安市| 资溪县| 西吉县| 射阳县| 陕西省| 长治县| 江达县| 崇文区| 漳州市| 鄂伦春自治旗| 洪洞县| 荥阳市| 登封市| 光山县| 南康市| 新宾| 同德县| 南召县| 惠东县| 正镶白旗| 太仆寺旗| 大名县| 永川市| 灌云县| 融水| 工布江达县| 田阳县|