Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. [(1,2),(3,4),(5,6),]
  2.  
  3. [1,3,5],[2,4,6]
  4.  
  5. >>> zip(*[(1, 2), (3, 4), (5, 6)])
  6. [(1, 3, 5), (2, 4, 6)]
  7.  
  8. map(list, zip(*[(1, 2), (3, 4), (5, 6)]))
  9.  
  10. >>> zip((1,3,5),(2,4,6))
  11. [(1, 2), (3, 4), (5, 6)]
  12. >>> zip(*[(1, 2), (3, 4), (5, 6)])
  13. [(1, 3, 5), (2, 4, 6)]
  14.  
  15. >>> map(list, zip(*[(1, 2), (3, 4), (5, 6)]))
  16. [[1, 3, 5], [2, 4, 6]]
  17.  
  18. a = [(1,2),(3,4),(5,6),]
  19. b = zip(*a)
  20. >>> [(1, 3, 5), (2, 4, 6)]
  21.  
  22. def t1(zs):
  23. xs, ys = zip(*zs)
  24. return xs, ys
  25.  
  26. def t2(zs):
  27. xs, ys = [], []
  28. for x, y in zs:
  29. xs.append(x)
  30. ys.append(y)
  31. return xs, ys
  32.  
  33. def t3(zs):
  34. xs, ys = [x for x, y in zs], [y for x, y in zs]
  35. return xs, ys
  36.  
  37. if __name__ == '__main__':
  38. from timeit import timeit
  39. setup_string='''
  40. N = 2000000
  41. xs = list(range(1, N))
  42. ys = list(range(N+1, N*2))
  43. zs = list(zip(xs, ys))
  44. from __main__ import t1, t2, t3
  45. '''
  46. print(f'zip:tt{timeit('t1(zs)', setup=setup_string, number=1000)}')
  47. print(f'append:tt{timeit('t2(zs)', setup=setup_string, number=1000)}')
  48. print(f'list comp:t{timeit('t3(zs)', setup=setup_string, number=1000)}')
  49.  
  50. zip: 122.11585397789766
  51. append: 356.44876132614047
  52. list comp: 144.637765085659
  53.  
  54. [[*x] for x in zip(*[(1,2),(3,4),(5,6)])]
  55. >>> [[1, 3, 5], [2, 4, 6]]
  56.  
  57. xs, ys = [], []
  58. for x, y in zs:
  59. xs.append(x)
  60. ys.append(y)
  61.  
  62. Using *zip: 1.54701614s
  63. Using append: 0.52687597s
  64.  
  65. #!/usr/bin/env python3
  66. import time
  67.  
  68. N = 2000000
  69. xs = list(range(1, N))
  70. ys = list(range(N+1, N*2))
  71. zs = list(zip(xs, ys))
  72.  
  73. t1 = time.time()
  74.  
  75. xs_, ys_ = zip(*zs)
  76. print(len(xs_), len(ys_))
  77.  
  78. t2 = time.time()
  79.  
  80. xs_, ys_ = [], []
  81. for x, y in zs:
  82. xs_.append(x)
  83. ys_.append(y)
  84. print(len(xs_), len(ys_))
  85.  
  86. t3 = time.time()
  87.  
  88. print('Using *zip:t{:.8f}s'.format(t2 - t1))
  89. print('Using append:t{:.8f}s'.format(t3 - t2))
  90.  
  91. Python 3.6.3 (default, Oct 24 2017, 12:18:40)
  92. [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
  93. Type "help", "copyright", "credits" or "license" for more information.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement