Python中的元组

300 阅读1分钟

元组不仅仅是不可变的列表

1、把元组用作记录           
 lax_coordinates = (33.9425, -118.408056)       
 city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)
 traveler_ids = [('USA', '323232'), ('BRA', '212121'), ('ESP', 'XDA205922')]              
 for passprt in sorted(traveler_ids):
    print('%s/%s' % passport)
------------------------------------------
BRA/212121    USA/323232   ESP/XDA205922
2、元组拆包
lax_coordinates = (33.9425, -118.408056)
latitude, longitude = lax_coordinates # 元组拆包 
--------------------------------------------
latitude   33.9425   longitude  -118.408056
3、具名元组
from collections import namedtuple   
City = namedtuple('City', 'name country population coordinates')
tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))  
tokyo City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667)) 
-------------------------------------------
tokyo.population   ----->  36.933
tokyo.coordinates  ----->  (35.689722, 139.691667)
tokyo[1]          ----->   JP

3.1 具名元组特有属性
除了从普通元组那里继承来的属性之外,具名元组还有一些自己专有的属性。
几个最有用的:_fields 类属性、类方法 _make(iterable) 和实例方法 _asdict()。 
>>> City._fields 
('name', 'country', 'population', 'coordinates')
>>> LatLong = namedtuple('LatLong', 'lat long')
>>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889)) 
>>> delhi = City._make(delhi_data)
>>> delhi._asdict()
OrderedDict([('name', 'Delhi NCR'), ('country', 'IN'), ('population', 21.935), ('coordinates', LatLong(lat=28.613889, long=77.208889))]) 
>>> for key, value in delhi._asdict().items():   
print(key + ':', value)
name: Delhi NCR country: IN population: 21.935 coordinates: LatLong(lat=28.613889, long=77.208889) 
>>>

_fields 属性是一个包含这个类所有字段名称的元组
_make() 通过接受一个可迭代对象来生成这个类的一个实例,它的作用跟 City(*delhi_data) 是一样的
_asdict() 把具名元组以 collections.OrderedDict 的形式返回,我们可以利用它 来把元组里的信息友好地呈现出来。