fork(3) download
  1. def replace():
  2. '''Using try-except'''
  3. myl = [1, 2, 3, 4, 5, 4, 4, 4, 4, 6, 6, 9, 4, 2, 2, 22, 99, 0, 100, 100, 34, 55]
  4. # myl.extend ([100] * 100)
  5. while True:
  6. try:
  7. myl[ myl.index (4) ] = 44
  8. except:
  9. break
  10.  
  11. def replace2():
  12. '''Using slice-assign'''
  13. myl = [1, 2, 3, 4, 5, 4, 4, 4, 4, 6, 6, 9, 4, 2, 2, 22, 99, 0, 100, 100, 34, 55]
  14. # myl.extend ([100] * 100)
  15.  
  16. myl[:] = [x if x != 4 else 44 for x in myl]
  17.  
  18. def replace3():
  19. '''Using enumerate'''
  20. myl = [1, 2, 3, 4, 5, 4, 4, 4, 4, 6, 6, 9, 4, 2, 2, 22, 99, 0, 100, 100, 34, 55]
  21. # myl.extend ([100] * 100)
  22.  
  23. for idx, item in enumerate(myl):
  24. if item == 4:
  25. myl[idx] = 44
  26.  
  27. import timeit
  28. #print(timeit.timeit("test()", setup="from __main__ import test"))
  29. print(timeit.timeit("replace()", setup="from __main__ import replace")), replace.func_doc
  30. print(timeit.timeit("replace2()", setup="from __main__ import replace2")), replace2.func_doc
  31. print(timeit.timeit("replace3()", setup="from __main__ import replace3")), replace3.func_doc
  32.  
Success #stdin #stdout 13.33s 7908KB
stdin
Standard input is empty
stdout
6.65385389328 None
3.40503907204 None
3.29963207245 None