在“ for循环”中每第三次迭代后进入睡眠状态

时间:2019-04-09 14:08:16

标签: python-3.x list for-loop

我正在尝试使脚本在“ for循环”中每第三次迭代后就进入睡眠状态。这是我到目前为止的内容:

 #List of words
 Word_list = ['apple','orange','grape','mango','berries','banana','sugar']

 #Loop through the list of words with the index and value of the list
 for i,word in enumerate(Word_list):
     #Store value of i in v
     v = i
     #If the value of the index, same as the 3rd loop iteration is 3, do this
     if v == 3*(i+1):
       sleep(3)
       print(i+1,word,'done')
     #Else do this
     else:
       print('exception')

输出不是我期望的。

预期输出为:

exception
exception
3,grape,done
exception
exception
6,banana,done
exception 

3 个答案:

答案 0 :(得分:1)

这应该做到。执行v = i然后检查v == 3 * (i + 1)总是为False,因为您正在检查i==3*(i+1),这对i=-1/2

是正确的
import time
Word_list = ['apple','orange','grape','mango','berries','banana','sugar']
#Loop through the list of words with the index and value of the list
for i,word in enumerate(Word_list, 1):
    #modulus function checks for divisibility by 3
    if (i %3 == 0):
        time.sleep(1)
        print(i,word,'done')
    #Else do this
    else:
       print('exception')

答案 1 :(得分:0)

您对if语句的条件没有达到您想要的目的。 v永远不会等于3*(i+1),因为您在循环中更早地设置了i=v。您想要做的是v乘以3的模数,该模数等于0,这样您就知道遍历列表已经三遍了。这就是代码的样子

import time
#List of words
Word_list = ['apple','orange','grape','mango','berries','banana','sugar']

#Loop through the list of words with the index and value of the list
for i,word in enumerate(Word_list):
    #Store value of i in v
    v = i
    #If the value of the index, same as the 3rd loop iteration is 3, do this
    if (v + 1) %3 == 0:
        time.sleep(3)
        print(i+1,word,'done')
    #Else do this
    else:
        print('exception')

给出以下输出:

exception
exception
3 grape done
exception
exception
6 banana done
exception

答案 2 :(得分:0)

这是一个变体:

from time import sleep

Word_list = ['apple', 'orange', 'grape', 'mango', 'berries', 'banana', 'sugar']

# Loop through the list of words with the index and value of the list
for i, word in enumerate(Word_list, start=1):
    if i % 3 == 0:
        sleep(3)
        print(i, word, 'done')
    else:
        print('exception')

诀窍是从1开始枚举,并检查i%3是否为零。