fork download
  1. def join(a):
  2. """Joins a sequence of sequences into a single sequence. (One-level flattening.)
  3. E.g., join([(1,2,3), [4, 5], [6, (7, 8, 9), 10]]) = [1,2,3,4,5,6,(7,8,9),10]
  4. This is very efficient, especially when the subsequences are long.
  5. """
  6. n = sum([len(b) for b in a])
  7. l = [None]*n
  8. i = 0
  9. for b in a:
  10. j = i+len(b)
  11. l[i:j] = b
  12. i = j
  13. return l
  14.  
  15. def join2(a):
  16. result = []
  17. for x in a:
  18. result.extend(x)
  19. return result
  20.  
  21. def join3(a):
  22. result = []
  23. map(result.extend, a)
  24. return result
  25.  
  26. def join4(a):
  27. return reduce(lambda l, r: l.extend(r) or l, a, [])
  28.  
  29. testdata = [range(t) for t in range(100, 200)]
  30.  
  31. import timeit, pprint
  32. results = [
  33. (funcname, timeit.timeit(lambda: func(testdata), number=150))
  34. for funcname, func in locals().items()
  35. if hasattr(func, '__call__')]
  36. pprint.pprint(sorted(results, key=lambda x: x[1]))
Success #stdin #stdout 0.17s 10960KB
stdin
Standard input is empty
stdout
[('join3', 0.015027999877929688),
 ('join2', 0.01589202880859375),
 ('join4', 0.019412994384765625),
 ('join', 0.03456687927246094)]