python - 如何仅记录/查看循环内的中间值或连续输入一次
问题描述
有时,在调试时,我只想记录/查看变量的内容 - 在 for 循环中 - 一次。当我处理输入流时也会发生同样的情况。有没有办法在 Python 中做到这一点。我想避免在每次迭代时记录变量内容,或者在稍后的时间点输入新输入时。我想避免使用布尔标志。只是想知道是否有提供相同功能的模块。谢谢!
一个潜在的场景 - 我想看看在处理第一个样本后存储在 outDict 中的内容:
for sample in manySamples:
outDict = {}
flag = process(sample,outDict) //function process sample and saves result in outDict
if flag:
#rest of the code
解决方案
如果您想根据迭代值执行此操作,最简单的方法是 through enumerate()
,假设您想检查您可以执行的每 3 次迭代的值:
for counter, sample in enumerate(manySamples):
outDict = {}
flag = process(sample,outDict) # function process sample and saves result in outDict
if counter % 3 == 0: # If the counter is a multiple of 3
# Here you would put the logging code for whatever values are relevant
if flag:
#rest of the code
由于我不知道此代码的完整上下文,因此在您的情况下这可能会更好,因为您似乎正在使用它flag
来分隔有用的值:
for counter, sample in enumerate(manySamples):
outDict = {}
flag = process(sample,outDict) # function process sample and saves result in outDict
if flag:
if counter % 3 == 0: # If the counter is a multiple of 3
# Here you would put the logging code for whatever values are relevant
# rest of the code
推荐阅读
- charts - 如何查找谷歌图表(Sankey)选择事件选择数据 - 包括工具提示列
- java - 如何找到将tools.jar排除在pom文件中的位置?
- facebook-graph-api - 使用 Graph API 为用户获取 Instagram 链接页面(Instagram 商业帐户)
- php - 如何修复这个关于 PHP 的 Centos 7 错误
- mongodb - MongoDB 中的复合分片键的工作方式类似于复合索引吗?
- excel - 动态运行存储在单元格中的宏
- spring-boot - 仅使用 https 的 Spring Boot - 测试失败
- flutter - 为什么 GetIt 库需要在后台应用程序时重新初始化(未终止)?
- javascript - 使用 Formik Form 检测 Input Chakra UI 元素的“删除”键 onKeyPress
- kubernetes - 使用外部 yaml 文件为 kubernetes 创建 configmap