In Python, you may need a counter when turning a for statement in a sequence. : smiley: At that time, it seems that the easy way is to define a counter outside the for statement and increment it inside the for statement, or to get the counter using enumerate: relaxed: When I heard that story, I wondered which one could process faster: confused: So I decided to measure the speed: grin: Click here for the measurement code.
sptst.py
import time
def count(test):
    count=0
    start=time.time()
    for item in test:
        a=count
        b=item
        c=test[count]
        count+=1
    diff=time.time()-start
    return diff
def enumer(test):
    start=time.time()
    for count,item in enumerate(test):
        a=count
        b=item
        c=test[count]
    diff=time.time()-start
    return diff
test=[]
for i in range(100000):
    test.append("test")
loopNum=1000
summation=0
for i in range(loopNum):
    summation+=(count(test))/(enumer(test))
print(summation/loopNum)
In the for statement using count and the for statement using enumerate, I turned the list consisting of 100000 elements and tried to perform appropriate processing. : neckbeard: Each for statement is turned 1000 times, and the count shows how many times the time has reached on average. : neckbeard: As a result, it settled down to about 1.2. : anguished: In this case, the processing was light, so there seems to be a 1.2 times difference: no_mouth: When you need a counter in a for statement, it seems better to use enumerate than to define a variable outside and increment it: wink:
Recommended Posts