Reputation: 136
I'm learning python, and I found myself on some bottleneck I don't understand.
The part where I wrote on the file is quick, but the iteration or maybe the creation of the list is really slow.
This snippet runs in something less than a second and it's not possible.
What I'm doing wrong? Thanks
import sys
import time
t0=time.time()
arr=list(range(1,10000))
for i in arr:
arr[arr.index(i)]= 'dsaijhjsdha' + str(i) + '\n'
open("bla.txt", "wb").write(bytearray(''.join(arr),'utf-8'))
d=time.time()-t0
print ("duration: %.2f s." % d)
Upvotes: 0
Views: 1769
Reputation: 2159
import sys
import time
t0=time.time()
arr=list(range(1,10000))
for i in arr:
arr[i-1]= 'dsaijhjsdha' + str(i) + '\n'
open("bla.txt", "wb").write(bytearray(''.join(arr),'utf-8'))
d=time.time()-t0
print ("duration: %.2f s." % d)
Have a look at the above solution. This will achieve the same output as you want.
Output: duration: 0.02 s.
Upvotes: 3
Reputation: 9580
You can do all of this in one line with list comprehension as:
Use this:
arr = ['dsaijhjsdha' + str(i) + '\n' for i in range(1, 10000)]
print(arr)
instead of:
arr=list(range(1,10000))
for i in arr:
arr[arr.index(i)]= 'dsaijhjsdha' + str(i) + '\n'
Using arr.index(i)
is unnecessarily adding to the cost of computation.
Upvotes: 1