python - 在“for循环”中每第三次迭代后休眠
问题描述
我试图让我的脚本在'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
解决方案
这应该这样做。做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')
推荐阅读
- nlp - 如何正确使用 LUIS ML 功能?
- testing - 赛普拉斯:比较两列:列值和日期值
- r - 使用 if_else 或 case_when 语句过滤表以在 R 中查找单行
- javascript - 在 Chrome 扩展程序中使用 ffmpeg.wasm 时出现意外异常
- postgresql - 使用继承创建的外部表卡住
- spring - Hiberatne 尝试为查看实体创建表
- r - 如何基于 R 中分组数据集中的二进制变量创建新变量?
- nginx - Nginx RTMP 分段文件名和时间戳
- reactjs - 强制在开发模式下做出本机反应以重新加载特定文件而不重置所有缓存
- android - Ionic Cordova Android 应用程序如何发布到华为应用程序库?