【问题标题】:Building a nested progress bar with postfixes in tqdm在 tqdm 中构建带有后缀的嵌套进度条
【发布时间】:2018-06-05 13:00:41
【问题描述】:

我知道如何使用 tqdm 构建嵌套进度条。

from tqdm import trange 
from time import sleep
for i in trange(10, desc='1st loop'):
    for j in trange(5, desc='2nd loop', leave=False):
        for k in trange(100, desc='3nd loop'): sleep(0.01)

我现在还有如何向栏添加后缀和描述

from tqdm import trange 
from random import random, randint 
from time import sleep 
with trange(100) as t: 
    for i in t: 
         t.set_description('GEN %i' % i) 
         t.set_postfix(loss=random(),  gen=randint(1,999), str='h', lst=[1, 2])   
         sleep(0.1)

问题

如何在 tqdm 的嵌套进度条中添加描述和后缀?我想为每个嵌套条添加独立的后缀。

【问题讨论】:

    标签: python progress-bar tqdm


    【解决方案1】:

    嵌套工作正常:

    from tqdm import trange
    from time import sleep
    
    n_epochs, n_steps = 5, 100
    with trange(1, n_epochs + 1, desc="All epochs") as epochs:
        for epoch in epochs:
            with trange(1, n_steps + 1, desc="Epoch {}/{}".format(epoch, n_epochs)) as steps:
                for step in steps:
                    epochs.set_postfix(foo=epoch * n_steps + step)
                    steps.set_postfix(bar="hello {}".format(step), baz=1 / step)
                    sleep(0.01)
    

    编辑

    运行时的输出如下所示(在本例中,我们处于第三个 epoch 的中间):

    Epoch 1/5: 100%|██████| 100/100 [00:01<00:00, 81.41it/s, bar=hello 100, baz=0.01]
    Epoch 2/5: 100%|██████| 100/100 [00:01<00:00, 81.04it/s, bar=hello 100, baz=0.01]
    All epochs:  40%|█████████▍              | 2/5 [00:03<00:04,  1.26s/it, foo=349]
    Epoch 3/5:  48%|███▎  | 48/100 [00:00<00:00, 79.08it/s, bar=hello 49, baz=0.0204]
    

    最后看起来是这样的:

    Epoch 1/5: 100%|██████| 100/100 [00:01<00:00, 81.41it/s, bar=hello 100, baz=0.01]
    Epoch 2/5: 100%|██████| 100/100 [00:01<00:00, 81.04it/s, bar=hello 100, baz=0.01]
    Epoch 3/5: 100%|██████| 100/100 [00:01<00:00, 80.23it/s, bar=hello 100, baz=0.01]
    Epoch 4/5: 100%|██████| 100/100 [00:01<00:00, 80.27it/s, bar=hello 100, baz=0.01]
    Epoch 5/5: 100%|██████| 100/100 [00:01<00:00, 80.20it/s, bar=hello 100, baz=0.01]
    All epochs: 100%|█████████████████████████| 5/5 [00:06<00:00,  1.24s/it, foo=600]
    

    【讨论】:

    • 我刚刚测试了这个。它真的不起作用。该栏将跨越新行。
    • @EduardoReis 感谢您的反馈。我不确定我明白你的意思。你运行了这个确切的代码吗?对我来说,输出很棒,每个时期只跨越一条线,再加上一条“所有时期”线。这就是您所说的“酒吧将跨越新行”的意思吗?
    • 我更新了答案以显示示例输出。
    • This answer 可能也有帮助。看看吧。
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多