python - Replace for-loop across week with list comprehension -


how replace following for loops more efficient list comprehension or similar? numpy , pandas not option not installed on client system, perhaps itertools useful?

n_day_cells      = 24*60/240 week_matrix      = list()  in range(7):     j in range(n_day_cells):         week_matrix.append([i,j,0]) 

edit: sorry, should perhaps have been bit more specific. i'm on python 2.7 no other packages "core" packages such itertools. code needs run ~1m-1b times in script.

you can using:

week_matrix = [[i,j,0] in range(7) j in range(n_day_cells)] 

in case ranges bigger , on python2, might want use xrange instead of range iterator.


if bent on saving more time, use xrange, , create list of tuples instead of list of lists (all examples in python2):

in [3]: %timeit [[i,j,0] in range(7) j in range(n_day_cells)] 100000 loops, best of 3: 6.51 µs per loop  in [4]: %timeit [(i,j,0) in range(7) j in range(n_day_cells)] 100000 loops, best of 3: 4.6 µs per loop  in [5]: %timeit [(i,j,0) in xrange(7) j in xrange(n_day_cells)] 100000 loops, best of 3: 4.09 µs per loop 

the last 1 above should fastest alternative if want use generator:

week_matrix = ((i,j,0) in xrange(7) j in xrange(n_day_cells)) 

the other answer provided map, though interesting, have more overhead because of repetitive calls lambda , call map:

in [6]: %timeit map(lambda x: [x//6, x%6, 0], xrange(n_day_cells*7)) 100000 loops, best of 3: 10.6 µs per loop 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -