namedtuple
来源:互联网 发布:ubuntu卸载qq2012 编辑:程序博客网 时间:2024/05/17 09:29
namedtuple¶
The standard tuple uses numerical indexes to access its members.
bob = ('Bob', 30, 'male')print 'Representation:', bobjane = ('Jane', 29, 'female')print '\nField by index:', jane[0]print '\nFields by index:'for p in [ bob, jane ]: print '%s is a %d year old %s' % p
This makes tuples convenient containers for simple uses.
$ python collections_tuple.pyRepresentation: ('Bob', 30, 'male')Field by index: JaneFields by index:Bob is a 30 year old maleJane is a 29 year old female
On the other hand, remembering which index should be used for each value can lead to errors, especially if thetuple has a lot of fields and is constructed far from where it is used. Anamedtuple assigns names, as well as the numerical index, to each member.
Defining¶
namedtuple instances are just as memory efficient as regular tuples because they do not have per-instance dictionaries. Each kind ofnamedtuple is represented by its own class, created by using thenamedtuple() factory function. The arguments are the name of the new class and a string containing the names of the elements.
import collectionsPerson = collections.namedtuple('Person', 'name age gender')print 'Type of Person:', type(Person)bob = Person(name='Bob', age=30, gender='male')print '\nRepresentation:', bobjane = Person(name='Jane', age=29, gender='female')print '\nField by name:', jane.nameprint '\nFields by index:'for p in [ bob, jane ]: print '%s is a %d year old %s' % p
As the example illustrates, it is possible to access the fields of thenamedtuple by name using dotted notation (obj.attr) as well as using the positional indexes of standard tuples.
$ python collections_namedtuple_person.pyType of Person: <type 'type'>Representation: Person(name='Bob', age=30, gender='male')Field by name: JaneFields by index:Bob is a 30 year old maleJane is a 29 year old female
Invalid Field Names¶
As the field names are parsed, invalid values causeValueError exceptions.
import collectionstry: collections.namedtuple('Person', 'name class age gender')except ValueError, err: print errtry: collections.namedtuple('Person', 'name age gender age')except ValueError, err: print err
Names are invalid if they are repeated or conflict with Python keywords.
$ python collections_namedtuple_bad_fields.pyType names and field names cannot be a keyword: 'class'Encountered duplicate field name: 'age'
In situations where a namedtuple is being created based on values outside of the control of the programm (such as to represent the rows returned by a database query, where the schema is not known in advance), set therename option to True so the fields are renamed.
import collectionswith_class = collections.namedtuple('Person', 'name class age gender', rename=True)print with_class._fieldstwo_ages = collections.namedtuple('Person', 'name age gender age', rename=True)print two_ages._fields
The field with name class becomes _1 and the duplicateage field is changed to_3.
$ python collections_namedtuple_rename.py('name', '_1', 'age', 'gender')('name', 'age', 'gender', '_3')
- namedtuple
- Python namedtuple
- python namedtuple
- Collections -- namedtuple
- Python namedtuple
- namedtuple使用
- python namedtuple
- Python namedtuple 用法
- Python-namedtuple,enum
- Python namedtuple使用详解
- Python namedtuple使用详解
- hackerrank Collections.namedtuple()
- python中namedtuple使用
- Python HackerRank|Collections.namedtuple(from collections import namedtuple)
- 关于Python3的collections.namedtuple和functools.namedtuple的探讨
- 命名元组 collections.namedtuple
- Python的namedtuple使用详解
- collections模块里的:namedtuple
- MVC 笔记——异常处理
- 大数乘法
- 找工作--笔试面试--准备9
- 第七周项目三之求某员工一周工资
- IOS backgroundfetch
- namedtuple
- c3p0配置详解<转贴>
- 获取表中某一列的值出现的次数
- 404页面 显示走失儿童信息
- 第八周项目一:分段函数求值
- 新一代站群软件
- restfus webservices获取数据的api方法
- 十个鲜为人知的 Linux 命令 - Part 4
- linux定时任务三