Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #-*- encoding: utf-8 -*-
- lax_coordinates = (33.9425, -118.408056)
- latitude, longitude = lax_coordinates # Tuple unpacking.
- # Tuple unpacking.
- city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)
- traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'),
- ('ESP', 'XDA205856')]
- for passport in sorted(traveler_ids):
- print('%s/%s' % passport)
- for country, _ in traveler_ids: # _ 는 더미 변수를 나타낸다.
- print(country)
- # Tuple unpacking example.
- divmod(20, 8)
- t = (20, 8)
- divmod(*t)
- quotient, remainder = divmod(*t)
- quotient, remainder
- import os
- # 관심 없는 부분은 _을 이용하여 언패킹 할 때 무시할 수 있다.
- _, filename = os.path.split('/hello/my/name/is.jpg')
- # 초과 항목을 잡기 위해 * 사용하기.
- a, b, *rest = range(5) # r = (0, 1, [2, 3, 4])
- a, b, *rest = range(3) # r = (0, 1, [2])
- a, b, *rest = range(2) # r = (0, 1, [])
- a, *body, c, d = range(5) #r = (0, [1, 2], 3, 4)
- # 튜플 언패킹은 내포된 구조체에도 적용할 수 있다는 장점이 있다.
- # 전문가를 위한 파이선 예제를 살펴보면, 2-8에서 튜플을 사용하는데, 사실 사전형
- # 변수를 사용하는 것이 더 편하지 않을까?
- 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.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, (latitnude, longitude) in metro_areas:
- if longitude <= 0:
- print(fmt, format(name, latitude, longigude))
- # 위의 fmt 형식은 나중에 코드 개선에서 적용하면 좋을 것 같다.
- # 튜플은 아주 편리하다. 그러나 레코드로 사용하기에는 부족한 점이 있다.
- # 때로는 필드에 이름을 붙일 필요가 있다. 그래서 namedtuple() 함수가 고안됨.
- # named tuple.
- from collections import namedtuple
- City = namedtuple('City', 'name country population coordinates')
- tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
- tokyo
- # when to use list, dictionary, tuple, set...
- # tuple is immutable....
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement