1. 程式人生 > >元組的拆包

元組的拆包

round name new 參數 表達 一個 現在 int res

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

元組的拆包