1,元组用作记录

>>> lax_coordinates = (33.9425, -118.408056)

    拆包

>>> latitude, longitude = lax_coordinates
>>> latitude
33.9425

    还可以用*运算符把一个可迭代对象拆开作为函数的参数

>>> t = (20, 8)
>>> quotient, remainder = divmod(*t)
>>> quotient, remainder
(2, 4)

     ps:*运算符用于平行赋值,当然*前缀只能用在一个变量名前面,不过可以出现在赋值表达式的任何位置。

>>> a, b, *rest = range(5)
>>> a, b, rest
(0,1,[2, 3, 4])
>>> a, *body, c, d = range(5)
>>> a, body, c, d
(0, [1,2], 3, 4)

2,嵌套元组拆包

metro_areas = [
    ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
    ('Delhi NCR', "IN", 21.935, (28.613889, 77.208889)),
    ('Mexico City', "MX", 20.142, (19.43333, -99.133333)),
    ('New York-Newark', "US", 20.104, (40.808611, -74.020386)),
    ('Sao Paulo', "BR", 19.649, (-23.547778, -46.635833)),
]
print('{:15}|{:^9}|{:^9}'.format("", 'lat.', 'long.'))
fmt = '{:15}|{:9.4f}|{:9.4f}'
for name, cc, pop, (latitude, longitude) in metro_areas: # 将元组的最后一个元素拆包
    if longitude <= 0:
        print(fmt.format(name, latitude, longitude))

输出

               |  lat.   |  long.  
Mexico City    |  19.4333| -99.1333
New York-Newark|  40.8086| -74.0204
Sao Paulo      | -23.5478| -46.6358

相关文章: