首页 > 解决方案 > 如何仅记录/查看循环内的中间值或连续输入一次

问题描述

有时,在调试时,我只想记录/查看变量的内容 - 在 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

标签: pythonpython-3.x

解决方案


如果您想根据迭代值执行此操作,最简单的方法是 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

推荐阅读