用*来处理剩下的元素

a, b, *c, d = range(10)
print(a)
print(b)
print(c)
print(d)
---
0
1
[2, 3, 4, 5, 6, 7, 8]
9

在python中,函数用*args来获取不确定数量的参数已经算是一种经典写法了.

嵌套元组拆包(元组拆包还有一个强大的功能,就是可以运用在嵌套结构中)

areas = [
    ('Tokyo','JP',36.933,(35.689722,139.691667)),
    ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
    ('Mexico City', 'MX', 20.142, (19.433333, -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, (lat, long) in areas:#变量构成的元组(lat,long)用来拆包元组的最后一个元素
    if long <= 0:
        print(fmt.format(name, lat, long))
        ---
                |   Lat.    |   Long.  
Mexico City     |   19.4333 |  -99.1333
New York-Newark |   40.8086 |  -74.0204
Sao Paulo       |  -23.5478 |  -46.6358
最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏