在tqdm中构建带有后缀的嵌套进度条

3
我知道如何使用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中为嵌套的进度条添加描述和后缀?我想为每个嵌套的进度条添加独立的后缀。

1个回答

2

嵌套正常:

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]

我刚刚测试了一下。它实际上不起作用。这个栏会跨越多行。 - Eduardo Reis
@EduardoReis 感谢您的反馈。我不确定我是否理解您的意思。您是否运行了这段完整的代码?对我来说,输出结果很好,每个时期只占据一行,并且还有一个“所有时期”行。您所说的“进度条会跨越多行”是指这个吗? - MiniQuark
我更新了我的答案,展示了一个样本输出。 - MiniQuark
这个答案可能也会有帮助。去看看吧。 - Eduardo Reis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接