tshirts = [(color, size) for color in colors for size in sizes] # [('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L')]
tshirts = [(color, size) for size in sizes for color in colors] # [('black', 'S'), ('white', 'S'), ('black', 'M'), ('white', 'M'), ('black', 'L'), ('white', 'L')]
元组不仅仅是不可变的列表
具名元组的一些方法
_fields(): 类方法,返回某个具名元组中的字段。
_make(iterable): 类方法,接收一个可迭代对象来生成类的实例。
_asdict(): 实例方法,返回以当前实例字段名为键,字段值为值的顺序字典。
演示如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
In [17]: City = collections.namedtuple('City', 'name country population coordinated')
In [18]: LatLong = collections.namedtuple('LatLong', 'lat long')
In [19]: delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
In [20]: delhi = City._make(delhi_data)
In [21]: City._fields Out[21]: ('name', 'country', 'population', 'coordinated')
与 list 相比,array 中存储的元素类型是在创建后就固定了的,且能够存储的元素类型也是固定的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
array(typecode [, initializer]) -> array
Type code C Type Minimum size in bytes 'b' signed integer 1 'B' unsigned integer 1 'u' Unicode character 2 (see note) 'h' signed integer 2 'H' unsigned integer 2 'i' signed integer 2 'I' unsigned integer 2 'l' signed integer 4 'L' unsigned integer 4 'q' signed integer 8 (see note) 'Q' unsigned integer 8 (see note) 'f' floating point 4 'd' floating point 8