百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

tqdm,一个高级的 Python 库! python trutle库

itomcoil 2024-12-26 13:59 24 浏览

大家好,今天为大家分享一个高级的 Python 库 - tqdm。

Github地址:https://github.com/tqdm/tqdm


在处理大规模数据或长时间运行的任务时,了解任务的进度对于用户体验和调试来说非常重要。tqdm 是一个用于显示进度条的 Python 库,它能将任务的进度信息直观地展示出来。无论是遍历一个大型列表、处理批量数据,还是下载文件,tqdm 都能轻松实现进度条显示,并且与 Python 的标准库和许多第三方库无缝集成。本文将详细介绍 tqdm 库,包括其安装方法、主要特性、基本和高级功能,以及实际应用场景,帮助全面了解并掌握该库的使用。

安装

要使用 tqdm 库,首先需要安装它。以下是安装步骤:

使用 pip 安装

可以通过 pip 直接安装 tqdm

pip install tqdm

特性

  1. 易于使用:只需添加一行代码即可在循环中显示进度条。
  2. 灵活性:支持多种进度条样式和自定义配置。
  3. 集成性:与 Python 的标准库(如 time、itertools)和许多第三方库(如 pandas、requests)无缝集成。
  4. 多平台支持:兼容 Linux、Windows 和 macOS 系统。
  5. 高性能:对性能影响较小,适用于大规模数据处理任务。

基本功能

基本用法

在遍历一个列表时使用 tqdm 显示进度条:

from tqdm import tqdm
import time

for i in tqdm(range(100)):
    time.sleep(0.1)

输出结果:

100%|██████████| 100/100 [00:10<00:00,  9.57it/s]

与enumerate结合使用

在遍历带索引的列表时使用 tqdm

from tqdm import tqdm
import time

for i, value in enumerate(tqdm(range(100))):
    time.sleep(0.1)

输出结果:

100%|██████████| 100/100 [00:10<00:00,  9.58it/s]

自定义进度条描述

可以自定义进度条的描述文字:

from tqdm import tqdm
import time

for i in tqdm(range(100), desc="Processing"):
    time.sleep(0.1)

输出结果:

Processing: 100%|██████████| 100/100 [00:10<00:00,  9.60it/s]

高级功能

嵌套进度条

tqdm 支持嵌套进度条,适用于多层循环的任务:

from tqdm import tqdm
import time

for i in tqdm(range(3), desc="Outer Loop"):
    for j in tqdm(range(10), desc="Inner Loop", leave=False):
        time.sleep(0.1)

输出结果:

Outer Loop:   0%|          | 0/3 [00:00<?, ?it/s]
Inner Loop:   0%|          | 0/10 [00:00<?, ?it/s]
Inner Loop:  10%|█         | 1/10 [00:00<00:00,  9.68it/s]
Inner Loop:  20%|██        | 2/10 [00:00<00:00,  9.66it/s]
Inner Loop:  30%|███       | 3/10 [00:00<00:00,  9.60it/s]
Inner Loop:  40%|████      | 4/10 [00:00<00:00,  9.58it/s]
Inner Loop:  50%|█████     | 5/10 [00:00<00:00,  9.63it/s]
Inner Loop:  60%|██████    | 6/10 [00:00<00:00,  9.72it/s]
Inner Loop:  70%|███████   | 7/10 [00:00<00:00,  9.64it/s]
Inner Loop:  80%|████████  | 8/10 [00:00<00:00,  9.60it/s]
Inner Loop:  90%|█████████ | 9/10 [00:00<00:00,  9.69it/s]
Inner Loop: 100%|██████████| 10/10 [00:01<00:00,  9.72it/s]
Outer Loop:  33%|███▎      | 1/3 [00:01<00:02,  1.04s/it]
Inner Loop:   0%|          | 0/10 [00:00<?, ?it/s]
Inner Loop:  10%|█         | 1/10 [00:00<00:00,  9.77it/s]
Inner Loop:  20%|██        | 2/10 [00:00<00:00,  9.65it/s]
Inner Loop:  30%|███       | 3/10 [00:00<00:00,  9.61it/s]
Inner Loop:  40%|████      | 4/10 [00:00<00:00,  9.58it/s]
Inner Loop:  50%|█████     | 5/10 [00:00<00:00,  9.59it/s]
Inner Loop:  60%|██████    | 6/10 [00:00<00:00,  9.57it/s]
Inner Loop:  70%|███████   | 7/10 [00:00<00:00,  9.59it/s]
Inner Loop:  80%|████████  | 8/10 [00:00<00:00,  9.55it/s]
Inner Loop:  90%|█████████ | 9/10 [00:00<00:00,  9.55it/s]
Inner Loop: 100%|██████████| 10/10 [00:01<00:00,  9.56it/s]
Outer Loop:  67%|██████▋   | 2/3 [00:02<00:01,  1.04s/it]
Inner Loop:   0%|          | 0/10 [00:00<?, ?it/s]
Inner Loop:  10%|█         | 1/10 [00:00<00:00,  9.95it/s]
Inner Loop:  20%|██        | 2/10 [00:00<00:00,  9.70it/s]
Inner Loop:  30%|███       | 3/10 [00:00<00:00,  9.71it/s]
Inner Loop:  40%|████      | 4/10 [00:00<00:00,  9.63it/s]
Inner Loop:  50%|█████     | 5/10 [00:00<00:00,  9.60it/s]
Inner Loop:  60%|██████    | 6/10 [00:00<00:00,  9.66it/s]
Inner Loop:  70%|███████   | 7/10 [00:00<00:00,  9.62it/s]
Inner Loop:  80%|████████  | 8/10 [00:00<00:00,  9.58it/s]
Inner Loop:  90%|█████████ | 9/10 [00:00<00:00,  9.68it/s]
Inner Loop: 100%|██████████| 10/10 [00:01<00:00,  9.67it/s]
Outer Loop: 100%|██████████| 3/3 [00:03<00:00,  1.04s/it]

与pandas结合使用

tqdm 可以与 pandas 无缝集成,显示 pandas 操作的进度条:

import pandas as pd
from tqdm import tqdm

tqdm.pandas()

df = pd.DataFrame({"a": range(1000)})
df.progress_apply(lambda x: x ** 2)

输出结果:

100%|██████████| 1/1 [00:00<00:00, 622.21it/s]

与requests结合使用

tqdm 可以与 requests 结合使用,显示文件下载的进度条:

import requests
from tqdm import tqdm

url = 'https://example.com/largefile.zip'
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))

with open('largefile.zip', 'wb') as file, tqdm(
    desc='Downloading',
    total=total_size,
    unit='B',
    unit_scale=True,
    unit_divisor=1024,
) as bar:
    for data in response.iter_content(chunk_size=1024):
        file.write(data)
        bar.update(len(data))

输出结果:

Downloading: 1.23kB [00:00, 509kB/s]

自定义进度条样式

tqdm 允许用户自定义进度条的样式:

from tqdm import tqdm
import time

for i in tqdm(range(100), bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt}"):
    time.sleep(0.1)

输出结果:

100%|██████████| 100/100

实际应用场景

数据处理与分析

在数据处理与分析中,通过 tqdm 显示数据处理的进度,提升用户体验。

from tqdm import tqdm
import pandas as pd

# 加载数据
df = pd.read_csv('large_dataset.csv')

# 数据处理
for index, row in tqdm(df.iterrows(), total=df.shape[0], desc="Processing Data"):
    # 进行一些数据处理操作
    pass

输出结果:

Processing Data: 100%|██████████| 242/242 [00:00<00:00, 20854.32it/s]

机器学习模型训练

在机器学习模型训练过程中,通过 tqdm 显示训练进度,方便监控和调试。

from tqdm import tqdm
import time

epochs = 2
batches = 5

for epoch in tqdm(range(epochs), desc="Epochs"):
    for batch in tqdm(range(batches), desc="Batches", leave=False):
        # 模拟训练过程
        time.sleep(0.1)

输出结果:

Epochs:   0%|          | 0/2 [00:00<?, ?it/s]
Batches:   0%|          | 0/5 [00:00<?, ?it/s]
Batches:  20%|██        | 1/5 [00:00<00:00,  9.84it/s]
Batches:  40%|████      | 2/5 [00:00<00:00,  9.77it/s]
Batches:  60%|██████    | 3/5 [00:00<00:00,  9.75it/s]
Batches:  80%|████████  | 4/5 [00:00<00:00,  9.69it/s]
Batches: 100%|██████████| 5/5 [00:00<00:00,  9.66it/s]
Epochs:  50%|█████     | 1/2 [00:00<00:00,  1.94it/s]
Batches:   0%|          | 0/5 [00:00<?, ?it/s]
Batches:  20%|██        | 1/5 [00:00<00:00,  9.74it/s]
Batches:  40%|████      | 2/5 [00:00<00:00,  9.78it/s]
Batches:  60%|██████    | 3/5 [00:00<00:00,  9.72it/s]
Batches:  80%|████████  | 4/5 [00:00<00:00,  9.65it/s]
Batches: 100%|██████████| 5/5 [00:00<00:00,  9.58it/s]
Epochs: 100%|██████████| 2/2 [00:01<00:00,  1.93it/s]

文件下载与上传

在文件下载与上传过程中,通过 tqdm 显示进度条,提升用户体验。

import requests
from tqdm import tqdm

url = 'https://example.com/largefile.zip'
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))

with open('largefile.zip', 'wb') as file, tqdm(
        desc='Downloading',
        total=total_size,
        unit='B',
        unit_scale=True,
        unit_divisor=1024,
) as bar:
    for data in response.iter_content(chunk_size=1024):
        file.write(data)
        bar.update(len(data))

输出结果:

Downloading: 1.23kB [00:00, 1.21MB/s]

总结

tqdm 库是一个功能强大且易于使用的进度条显示工具,能够帮助开发者在处理大规模数据或长时间运行的任务时直观地了解任务进度。通过支持易于使用、灵活性、集成性、多平台支持和高性能,tqdm 提供了强大的功能和灵活的扩展能力。本文详细介绍了 tqdm 库的安装方法、主要特性、基本和高级功能,以及实际应用场景。希望本文能帮助大家全面掌握 tqdm 库的使用,并在实际项目中发挥其优势。无论是在数据处理与分析、机器学习模型训练还是文件下载与上传中,tqdm 库都将是一个得力的工具。

相关推荐

Python 类型注解的进阶应用:从静态检查到元编程

阅读文章前辛苦您点下“关注”,方便讨论和分享,为了回馈您的支持,我将每日更新优质内容。如需转载请附上本文源链接!近年来,Python类型注解(TypeHinting)逐渐从一个可选的功能演变为大型...

高阶Python|返回类型提示技巧 (1)

引言Python提供了一种可选的特性——类型提示,它有助于提高代码的可读性、可推理性和可调试性。通过类型提示,开发者能够清楚地了解变量、函数参数和返回值应具备的数据类型。在开发那些需要高度灵活性的应用...

跟我一起学Python-函数的定义(基础)

一.函数的定义和调用1.语法:def函数名():函数封装的代码函数最好能够表达函数内部封装的代码功能,方便后续的调用,函数命名需要遵循规则字母、数字、下划线、不能以数字开头,不能使用系统关键字。&#...

Python函数参数和返回值类型:让你的代码更清晰、更健壮

在Python开发中,你是否遇到过这些抓狂时刻?同事写的函数参数类型全靠猜调试两小时发现传了字符串给数值计算函数重构代码时不知道函数返回的是列表还是字典今天教你两招,彻底解决类型混乱问题!让你的...

python入门到脱坑 函数—参数(python 参数处理)

本文包括必须参数,关键参数,默认参数以及可变参数Python函数参数详解一、位置参数(必需参数)位置参数是函数调用时必须提供的参数,且顺序必须与定义时一致。基本用法defgreet(name,me...

python入门到脱坑经典案例—求两个数的和

下面为大家讲解如何求两个数之和——这是编程中最基础但最重要的算术运算之一。我们会从最简单的情况逐步深入,并穿插相关编程概念。1.最基础版本#定义两个变量num1=5num2=3#...

新手必看!30 个 Python 核心函数详解,手把手教你玩转编程

Python中30个核心函数及其含义、代码示例、注释和应用场景:print():用于输出文本或变量的值到控制台。message="Hello,World!"#定义一个...

Python快速入门教程1:基本语法、数据类型、运算符、数字字符串

Python3的基础教程,涵盖了基本语法、数据类型、类型转换、解释器、注释、运算符、数字和字符串等内容,并附有使用实例场景。Python3的基础教程,涵盖了基本语法、数据类型、类型转换、解释器、注释、...

编程小白学做题:Python 的经典编程题及详解,附代码和注释(八)

适合Python3+的6道编程练习题(附详解)1找出字典中值最小的键题目描述:找出字典中值最小的键(如{"a":5,"b":2,"c...

新手学Python避坑,学习效率狂飙! 二十一、print()函数

感谢大家对《新手学Python避坑,学习效率狂飙!》系列的点赞、关注和收藏,今天这编是这个系列的第二十一个分享,前面还有二十个,大家可以关注下之前发布的文章。下面是我们今天第三个的分享:在Pytho...

编程小白学做题:Python 的经典编程题及详解,附代码和注释(六)

适合Python3+的6道编程练习题(附详解)1、打印杨辉三角的前n行题目描述:给定正整数n,打印杨辉三角的前n行(每个数等于它上方两数之和,每行首尾为1)。编写思路:杨辉三角的第i...

让你的Python代码更易读:7个提升函数可读性的实用技巧

如果你正在阅读这篇文章,很可能你已经用Python编程有一段时间了。今天,让我们聊聊可以提升你编程水平的一件事:编写易读的函数。请想一想:我们花在阅读代码上的时间大约是写代码的10倍。所以,每当你创建...

python入门到脱坑 函数—return语句

Python函数中的return语句详解一、return语句基础1.1基本功能return语句用于从函数中返回一个值,并立即结束函数的执行。defadd(a,b):returna+...

编程小白学做题:Python 的经典编程题及详解,附代码和注释(七)

适合Python3+的6道编程练习题(附详解)1.检查字符串是否以指定子串开头题目描述:判断字符串是否以给定子串开头(如"helloworld"以"hello&...

python的注释符是什么(python的合法注释符号是什么)

python的注释符是什么?python的注释符包括单行注释符和多行注释符。一、python单行注释符号(#)井号(#)常被用作单行注释符号,在代码中使用#时,它右边的任何数据都会被忽略,当做是注释。...