- Python Data Structures and Algorithms
- Benjamin Baka
- 365字
- 2021-07-09 19:45:06
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)
- Spring 5.0 By Example
- Apache Oozie Essentials
- 自己動(dòng)手實(shí)現(xiàn)Lua:虛擬機(jī)、編譯器和標(biāo)準(zhǔn)庫
- Effective C#:改善C#代碼的50個(gè)有效方法(原書第3版)
- Hands-On Data Structures and Algorithms with JavaScript
- 碼上行動(dòng):零基礎(chǔ)學(xué)會(huì)Python編程(ChatGPT版)
- CouchDB and PHP Web Development Beginner’s Guide
- SQL Server 2016數(shù)據(jù)庫應(yīng)用與開發(fā)習(xí)題解答與上機(jī)指導(dǎo)
- 概率成形編碼調(diào)制技術(shù)理論及應(yīng)用
- 焊接機(jī)器人系統(tǒng)操作、編程與維護(hù)
- Mastering Android Game Development
- Mastering Backbone.js
- RealSenseTM互動(dòng)開發(fā)實(shí)戰(zhàn)
- Python+Tableau數(shù)據(jù)可視化之美
- Creating Data Stories with Tableau Public