Python tqdm的两种用法【教程】

Python tqdm的两种用法

本文记录一下在学习深度强化学习过程中遇到tqdm库显示进度条的用法,以供大家交流。

注意本文使用的tqdm均是使用的tqdm库中的同名tqdm方法,应该按照如下方式导入

python 复制代码
from tqdm import tqdm

Catologue

  • [Python tqdm的两种用法](#Python tqdm的两种用法)
    • [1. 基于可迭代的用法 (Iterable-based)](#1. 基于可迭代的用法 (Iterable-based))
    • [2. 手动方式的用法(Manual)](#2. 手动方式的用法(Manual))
    • Reference

1. 基于可迭代的用法 (Iterable-based)

该种用法比较简单,直接使用tqdm包裹可迭代对象即可,例如

python 复制代码
from tqdm import tqdm
import time

for _ in  tqdm(range(30)):
    time.sleep(0.1)

结果如下

bash 复制代码
100%|██████████| 30/30 [00:03<00:00,  9.20it/s]

循环外部的实例化允许手动​​控制 tqdm()

python 复制代码
from tqdm import tqdm
import time
pbar = tqdm(["a", "b", "c", "d"])

for char in pbar:
    time.sleep(0.25)
    pbar.set_description("Processing %s" % char)

结果如下

bash 复制代码
Processing d: 100%|██████████| 4/4 [00:01<00:00,  3.83it/s]

2. 手动方式的用法(Manual)

利用python中的上下文管理器with来手动使用tqdm,其中初始化参数如下

python 复制代码
def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
                 ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
                 ascii=None, disable=False, unit='it', unit_scale=False,
                 dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0,
                 position=None, postfix=None, unit_divisor=1000, write_bytes=False,
                 lock_args=None, nrows=None, colour=None, delay=0, gui=False,
                 **kwargs):
        """
        Parameters
        ----------
        iterable  : iterable, optional
            Iterable to decorate with a progressbar.
            Leave blank to manually manage the updates.
        desc  : str, optional
            Prefix for the progressbar. 设置进度条的描述
        total  : int or float, optional 进度条总长
            The number of expected iterations. If unspecified,
            len(iterable) is used if possible. If float("inf") or as a last
            resort, only basic progress statistics are displayed
            (no ETA, no progressbar).
            If `gui` is True and this parameter needs subsequent updating,
            specify an initial arbitrary large positive number,
            e.g. 9e9.
        leave  : bool, optional
            If [default: True], keeps all traces of the progressbar
            upon termination of iteration.
            If `None`, will leave only if `position` is `0`.

例如

python 复制代码
from tqdm import tqdm
import time

with tqdm(total=100) as pbar:	#进度条总长100%

    for i in range(10):
        time.sleep(0.1)
        pbar.update(10)	#每次更新进度条10%

结果如下

python 复制代码
100%|██████████| 100/100 [00:01<00:00, 91.47it/s]

再例如,同时保留多个进度条,其中在使用 tqdm 库时,set_postfix 方法用于在进度条中显示附加信息。它允许在进度条的右侧显示一些额外的信息,比如当前迭代的一些指标或状态。

set_postfix 方法可以接受一个字典作为参数,其中键值对表示要显示的附加信息。调用此方法后,进度条会更新并在右侧显示传入的信息。

python 复制代码
from tqdm import tqdm
import time
num_episodes = 100 #最大的迭代次数
num_tqdm = 10 #进度条的数量
for i in range(num_tqdm):
    with tqdm(total= num_episodes/num_tqdm, desc="Iteration %d" %i) as pbar:
        for i_episode in range(int(num_episodes/num_tqdm)):
            time.sleep(0.1)
            pbar.update(1)	# 更新一次tqdm
            if (i_episode+1) % 10 == 0:
            # tqdm控制输出
                pbar.set_postfix({
                    "episode": "%d"%(num_episodes / num_tqdm * i + i_episode + 1) 
                })

结果如下

bash 复制代码
Iteration 0: 100%|██████████| 10/10.0 [00:01<00:00,  9.15it/s, episode=10]
Iteration 1: 100%|██████████| 10/10.0 [00:01<00:00,  9.17it/s, episode=20]
Iteration 2: 100%|██████████| 10/10.0 [00:01<00:00,  9.19it/s, episode=30]
Iteration 3: 100%|██████████| 10/10.0 [00:01<00:00,  9.18it/s, episode=40]
Iteration 4: 100%|██████████| 10/10.0 [00:01<00:00,  9.19it/s, episode=50]
Iteration 5: 100%|██████████| 10/10.0 [00:01<00:00,  9.23it/s, episode=60]
Iteration 6: 100%|██████████| 10/10.0 [00:01<00:00,  9.23it/s, episode=70]
Iteration 7: 100%|██████████| 10/10.0 [00:01<00:00,  9.23it/s, episode=80]
Iteration 8: 100%|██████████| 10/10.0 [00:01<00:00,  9.24it/s, episode=90]
Iteration 9: 100%|██████████| 10/10.0 [00:01<00:00,  9.19it/s, episode=100]

Reference

tqdm官方github

相关推荐
dy17179 分钟前
element-plus表格默认展开有子的数据
前端·javascript·vue.js
float_六七1 小时前
IntelliJ IDEA双击Ctrl的妙用
java·ide·intellij-idea
能摆一天是一天2 小时前
JAVA stream().flatMap()
java·windows
CodeCraft Studio3 小时前
PDF处理控件Aspose.PDF教程:使用 Python 将 PDF 转换为 Base64
开发语言·python·pdf·base64·aspose·aspose.pdf
颜如玉3 小时前
🤲🏻🤲🏻🤲🏻临时重定向一定要能重定向🤲🏻🤲🏻🤲🏻
java·http·源码
2501_915918414 小时前
Web 前端可视化开发工具对比 低代码平台、可视化搭建工具、前端可视化编辑器与在线可视化开发环境的实战分析
前端·低代码·ios·小程序·uni-app·编辑器·iphone
困鲲鲲4 小时前
Python中内置装饰器
python
摩羯座-185690305944 小时前
Python数据可视化基础:使用Matplotlib绘制图表
大数据·python·信息可视化·matplotlib
程序员的世界你不懂4 小时前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
星空寻流年4 小时前
设计模式第一章(建造者模式)
java·设计模式·建造者模式