简体   繁体   中英

How to write this for loop as map function

I read that map can be used more efficiently for iterations than for loops . How would I use map on this for loop :

import time
start = time.time()

L = []
a = 5
b = 0
for i in range(1000):
    L.append(i)
    b +=a


print(L)
print(b)
end = time.time()
print(end-start)

If you really want to use map :

L = []
a, b = 5, 0

list(map(L.append, range(1000)))
# or sum(map(bool, map(L.append, range(1000)))) - doesn't waste memory

b = a * len(L)

Note that for the calls to L.append to be executed, you need to iterate over the output of map , which is what list and sum do in this code.

You don't need use it in this case, however. This looks and performs better:

L = list(range(1000))

If you're using Python 2, you could just do L = range(1000) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM