什么是命名元组,我如何使用它们? 什么时候我应该使用命名元组而不是正常的元组,反之亦然? 也有“名单”吗?(即可变命名元组)


关于最后一个问题,请参见Python中是否存在可变命名元组。


当前回答

命名元组允许与这样检查版本的代码向后兼容

>>> sys.version_info[0:2]
(3, 1)

同时通过使用此语法允许未来的代码更加显式

>>> sys.version_info.major
3
>>> sys.version_info.minor
1

其他回答

命名元组是一个很好的特性,它们是数据的完美容器。当你必须“存储”数据时,你会使用元组或字典,比如:

user = dict(name="John", age=20)

or:

user = ("John", 20)

字典方法是压倒性的,因为字典是可变的,比元组慢。另一方面,元组是不可变和轻量级的,但是对于数据字段中的大量条目缺乏可读性。

命名元组是这两种方法的完美折衷,它们具有很高的可读性、轻量级性和不可变性(而且它们是多态的!)

试试这个:

collections.namedtuple()

基本上,命名元组很容易创建,轻量级的对象类型。 它们将元组转换为用于简单任务的方便容器。 使用namedtuples,您不必使用整数索引访问元组的成员。

例子:

代码1:

>>> from collections import namedtuple

>>> Point = namedtuple('Point','x,y')

>>> pt1 = Point(1,2)

>>> pt2 = Point(3,4)

>>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )

>>> print dot_product
11

代码2:

>>> from collections import namedtuple

>>> Car = namedtuple('Car','Price Mileage Colour Class')

>>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y')

>>> print xyz

Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y')
>>> print xyz.Class
Y

命名元组允许与这样检查版本的代码向后兼容

>>> sys.version_info[0:2]
(3, 1)

同时通过使用此语法允许未来的代码更加显式

>>> sys.version_info.major
3
>>> sys.version_info.minor
1

Namedtuple是一个用于创建元组类的工厂函数。通过这个类,我们还可以创建可按名称调用的元组。

import collections

#Create a namedtuple class with names "a" "b" "c"
Row = collections.namedtuple("Row", ["a", "b", "c"])   

row = Row(a=1,b=2,c=3) #Make a namedtuple from the Row class we created

print row    #Prints: Row(a=1, b=2, c=3)
print row.a  #Prints: 1
print row[0] #Prints: 1

row = Row._make([2, 3, 4]) #Make a namedtuple from a list of values

print row   #Prints: Row(a=2, b=3, c=4)

我认为添加使用类型提示的NamedTuples的信息是值得的:

# dependencies
from typing import NamedTuple, Optional

# definition
class MyNamedTuple(NamedTuple):
    an_attribute: str
    my_attribute: Optional[str] = None
    next_attribute: int = 1

# instantiation
my_named_tuple = MyNamedTuple("abc", "def")
# or more explicitly:
other_tuple = MyNamedTuple(an_attribute="abc", my_attribute="def")

# access
assert "abc" == my_named_tuple.an_attribute
assert 1 == other_tuple.next_attribute