Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #-*- encoding: utf-8 -*-
  2.  
  3. lax_coordinates = (33.9425, -118.408056)
  4.  
  5. latitude, longitude = lax_coordinates # Tuple unpacking.
  6.  
  7. # Tuple unpacking.
  8. city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)
  9.  
  10. traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'),
  11. ('ESP', 'XDA205856')]
  12.  
  13. for passport in sorted(traveler_ids):
  14. print('%s/%s' % passport)
  15.  
  16. for country, _ in traveler_ids: # _ 는 더미 변수를 나타낸다.
  17. print(country)
  18.  
  19. # Tuple unpacking example.
  20. divmod(20, 8)
  21. t = (20, 8)
  22. divmod(*t)
  23. quotient, remainder = divmod(*t)
  24. quotient, remainder
  25.  
  26. import os
  27.  
  28. # 관심 없는 부분은 _을 이용하여 언패킹 할 때 무시할 수 있다.
  29. _, filename = os.path.split('/hello/my/name/is.jpg')
  30.  
  31. # 초과 항목을 잡기 위해 * 사용하기.
  32. a, b, *rest = range(5) # r = (0, 1, [2, 3, 4])
  33. a, b, *rest = range(3) # r = (0, 1, [2])
  34. a, b, *rest = range(2) # r = (0, 1, [])
  35.  
  36. a, *body, c, d = range(5) #r = (0, [1, 2], 3, 4)
  37.  
  38. # 튜플 언패킹은 내포된 구조체에도 적용할 수 있다는 장점이 있다.
  39.  
  40. # 전문가를 위한 파이선 예제를 살펴보면, 2-8에서 튜플을 사용하는데, 사실 사전형
  41. # 변수를 사용하는 것이 더 편하지 않을까?
  42.  
  43. metro_areas = [
  44. ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
  45. ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
  46. ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
  47. ('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
  48. ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
  49. ]
  50.  
  51. print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
  52. fmt = '{:15} | {:9.4f} | {:9.4f}'
  53. for name, cc, pop, (latitnude, longitude) in metro_areas:
  54. if longitude <= 0:
  55. print(fmt, format(name, latitude, longigude))
  56.  
  57. # 위의 fmt 형식은 나중에 코드 개선에서 적용하면 좋을 것 같다.
  58. # 튜플은 아주 편리하다. 그러나 레코드로 사용하기에는 부족한 점이 있다.
  59. # 때로는 필드에 이름을 붙일 필요가 있다. 그래서 namedtuple() 함수가 고안됨.
  60.  
  61.  
  62. # named tuple.
  63. from collections import namedtuple
  64. City = namedtuple('City', 'name country population coordinates')
  65. tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
  66. tokyo
  67.  
  68. # when to use list, dictionary, tuple, set...
  69. # tuple is immutable....
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement