Python 常用库:tqdm

进度条 yyds!

简单版本:https://blog.csdn.net/qq_44168690/article/details/104116406

tqdm

tqdm 是一个快速,可扩展的 Python 进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm (iterator)。

使用 pip 就可以安装。

pip install tqdm

用例一:tqdm

tqdm (list) 方法可以传入任意一种 list, 比如数组

import time
from tqdm import tqdm

for i in tqdm(range(1000)):  
     #do something
     time.sleep(0.5)  

用例二:trange

trange (i) 是 tqdm (range (i)) 的简单写法

from tqdm import trange
for i in trange(100):
    #do something
    pass

用例三:带参数

from tqdm import tqdm
import time
d = {'loss':0.2,'learn':0.8}
#desc设置名称, ncols设置进度条长度, postfix以字典形式传入详细信息
for i in tqdm(range(50), desc='进行中', postfix=d): 
    time.sleep(0.1)

效果

在这里插入图片描述

用例四:用 tqdm 处理列表中的对象,显示处理进度

import time
from tqdm import tqdm

bar = tqdm(['p1','p2','p3','p4','p5'])
for b in bar:
    bar.set_description("处理 {0} 中".format(b))
    time.sleep(0.5)

效果

在这里插入图片描述

更多用例:

class tqdm(Comparable):
	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=None, lock_args=None,
                 nrows=None,
                 gui=False, **kwargs):

参数:

  • desc:进度条的前缀
  • ncols:输出信息的宽度。注意:如果设置的宽度过窄,将导致输出的信息显示不全!

完整说明如下:

        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`.
        file  : `io.TextIOWrapper` or `io.StringIO`, optional
            Specifies where to output the progress messages
            (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
            methods.  For encoding, see `write_bytes`.
        ncols  : int, optional
            The width of the entire output message. If specified,
            dynamically resizes the progressbar to stay within this bound.
            If unspecified, attempts to use environment width. The
            fallback is a meter width of 10 and no limit for the counter and
            statistics. If 0, will not print any meter (only stats).
        mininterval  : float, optional
            Minimum progress display update interval [default: 0.1] seconds.
        maxinterval  : float, optional
            Maximum progress display update interval [default: 10] seconds.
            Automatically adjusts `miniters` to correspond to `mininterval`
            after long display update lag. Only works if `dynamic_miniters`
            or monitor thread is enabled.
        miniters  : int or float, optional
            Minimum progress display update interval, in iterations.
            If 0 and `dynamic_miniters`, will automatically adjust to equal
            `mininterval` (more CPU efficient, good for tight loops).
            If > 0, will skip display of specified number of iterations.
            Tweak this and `mininterval` to get very efficient loops.
            If your progress is erratic with both fast and slow iterations
            (network, skipping items, etc) you should set miniters=1.
        ascii  : bool or str, optional
            If unspecified or False, use unicode (smooth blocks) to fill
            the meter. The fallback is to use ASCII characters " 123456789#".
        disable  : bool, optional
            Whether to disable the entire progressbar wrapper
            [default: False]. If set to None, disable on non-TTY.
        unit  : str, optional
            String that will be used to define the unit of each iteration
            [default: it].
        unit_scale  : bool or int or float, optional
            If 1 or True, the number of iterations will be reduced/scaled
            automatically and a metric prefix following the
            International System of Units standard will be added
            (kilo, mega, etc.) [default: False]. If any other non-zero
            number, will scale `total` and `n`.
        dynamic_ncols  : bool, optional
            If set, constantly alters `ncols` and `nrows` to the
            environment (allowing for window resizes) [default: False].
        smoothing  : float, optional
            Exponential moving average smoothing factor for speed estimates
            (ignored in GUI mode). Ranges from 0 (average speed) to 1
            (current/instantaneous speed) [default: 0.3].
        bar_format  : str, optional
            Specify a custom bar string formatting. May impact performance.
            [default: '{l_bar}{bar}{r_bar}'], where
            l_bar='{desc}: {percentage:3.0f}%|' and
            r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
              '{rate_fmt}{postfix}]'
            Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
              percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
              rate, rate_fmt, rate_noinv, rate_noinv_fmt,
              rate_inv, rate_inv_fmt, postfix, unit_divisor,
              remaining, remaining_s.
            Note that a trailing ": " is automatically removed after {desc}
            if the latter is empty.
        initial  : int or float, optional
            The initial counter value. Useful when restarting a progress
            bar [default: 0]. If using float, consider specifying `{n:.3f}`
            or similar in `bar_format`, or specifying `unit_scale`.
        position  : int, optional
            Specify the line offset to print this bar (starting from 0)
            Automatic if unspecified.
            Useful to manage multiple bars at once (eg, from threads).
        postfix  : dict or *, optional
            Specify additional stats to display at the end of the bar.
            Calls `set_postfix(**postfix)` if possible (dict).
        unit_divisor  : float, optional
            [default: 1000], ignored unless `unit_scale` is True.
        write_bytes  : bool, optional
            If (default: None) and `file` is unspecified,
            bytes will be written in Python 2. If `True` will also write
            bytes. In all other cases will default to unicode.
        lock_args  : tuple, optional
            Passed to `refresh` for intermediate output
            (initialisation, iterating, and updating).
        nrows  : int, optional
            The screen height. If specified, hides nested bars outside this
            bound. If unspecified, attempts to use environment height.
            The fallback is 20.
        gui  : bool, optional
            WARNING: internal parameter - do not use.
            Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
            matplotlib animations for a graphical output [default: False].

        Returns
        -------
        out  : decorated iterator.

参考:

https://blog.csdn.net/zkp_987/article/details/81748098

https://blog.csdn.net/feiyang5260/article/details/100050539

<think>好的,用户现在问的是Python常用,我需要先整理一下思路。首先,用户可能刚开始学Python,或者已经有一定基础,想了解有哪些常用可以使用。用户之前的问题是关于PyCharm项目中的包管理,可能现在想进一步了解常用,以便在项目中应用。 接下来,我需要确定Python常用的分类,这样才能让回答结构清晰。通常可以分为数据科学、Web开发、GUI开发、自动化、网络请求、图像处理、机器学习、异步编程等类别。每个类别下列举几个最常用,并简要说明其用途和特点。 还要注意用户可能的实际需求,比如他们可能在做数据分析、Web开发或者自动化脚本,所以需要针对不同方向推荐。同时,用户可能对某些的安装和使用有疑问,但根据之前的对话,他们已经了解了环境管理的问题,所以这里可能不需要再详细讲安装,但可以提到如何通过pip安装。 需要确保信息准确,比如的最新版本、维护状态等。例如,提到requests时,要确认它仍然是广泛使用的HTTP。对于机器学习,TensorFlow和PyTorch都是必须提到的,同时scikit-learn作为传统机器学习也很重要。 还要考虑用户可能对某些不熟悉,需要给出简单的示例代码,比如用pandas读取数据,或者用requests发送GET请求。这些示例能帮助用户快速理解的用途。 另外,要提醒用户根据项目需求选择合适的,避免不必要的依赖。比如小型项目可能不需要用Django,而Flask更轻量。同时,可以提到虚拟环境的重要性,呼应之前的问题,确保他们知道如何管理不同项目的依赖。 最后,总结部分要强调掌握这些对开发效率的提升,并鼓励用户深入学习和实践。可能还需要检查是否有遗漏的重要,比如日志处理的logging,或者测试框架pytest,但根据常见程度,可能集中在最核心的上。 需要确保使用中文,避免专业术语过多,必要时用通俗的语言解释。结构上使用标题和子标题,使内容易于浏览,重点部分用粗体或列表突出。同时,遵循之前设定的格式要求,比如行内公式用$...$,独立公式用$$...$$,但在这个问题中可能用不到数学公式,所以主要注意代码块和结构清晰。</think>以下是Python常用的全面分类介绍(基于应用场景和流行度): --- ### 一、**数据科学三剑客** | 名 | 用途 | 亮点功能 | 安装量(2023) | |------------|--------------------------|---------------------------|--------------| | **NumPy** | 多维数组运算 | `ndarray`数据结构 | 1.5亿+ | | **Pandas** | 数据分析与清洗 | `DataFrame`表格操作 | 1.8亿+ | | **Matplotlib** | 数据可视化 | 支持多种图表类型 | 1.2亿+ | **典型代码**: ```python import pandas as pd df = pd.read_csv('data.csv') print(df.describe()) ``` --- ### 二、**Web开发必备** 1. **Django** - 全栈框架(自带ORM、模板引擎) - 适合中大型项目(如Instagram后台) ```bash pip install django ``` 2. **Flask** - 微型框架(灵活扩展) - RESTful API开发首选 ```python from flask import Flask app = Flask(__name__) ``` 3. **FastAPI** - 高性能API框架(异步支持) - 自动生成Swagger文档 --- ### 三、**自动化与爬虫** | 名 | 应用场景 | 特点 | |---------------|------------------------|--------------------------| | **Requests** | HTTP请求 | 人类友好型API设计 | | **BeautifulSoup** | HTML解析 | 支持多种解析器 | | **Selenium** | 浏览器自动化 | 模拟真实用户操作 | **爬虫示例**: ```python import requests from bs4 import BeautifulSoup res = requests.get('https://example.com') soup = BeautifulSoup(res.text, 'html.parser') print(soup.title.text) ``` --- ### 四、**机器学习与AI** 1. **Scikit-learn** - 传统机器学习算法(分类/回归/聚类) - 包含经典数据集(鸢尾花数据集等) 2. **TensorFlow/PyTorch** - 深度学习框架双雄 - TensorFlow适合生产部署,PyTorch适合研究 3. **OpenCV** - 计算机视觉处理 - 人脸识别、图像滤波等 --- ### 五、**效率工具** 1. **Jupyter Notebook** - 交互式编程环境(支持Markdown) ```bash pip install jupyterlab ``` 2. **Tqdm** - 进度条工具(减少等待焦虑) ```python from tqdm import tqdm for i in tqdm(range(10000)): # 耗时操作 ``` 3. **Logging** - 日志记录标准 ```python import logging logging.basicConfig(level=logging.INFO) ``` --- ### 六、**跨领域实用** | 名 | 功能 | 典型应用场景 | |---------------|------------------------|-------------------------| | **PyQt5** | 图形界面开发 | 开发桌面应用程序 | | **SQLAlchemy**| 数据ORM | 简化SQL操作 | | **Asyncio** | 异步编程 | 高并发网络请求处理 | --- ### 最佳实践建议 1. **按需选择**:小型项目避免引入重型框架(如Django) 2. **版本控制**:使用`requirements.txt`记录依赖版本 ```bash pip freeze > requirements.txt ``` 3. **虚拟环境**:始终在项目专属环境中安装(呼应前文PyCharm环境问题) > **数据来源**:PyPI官方下载统计`pypistats`显示,截至2023年8月,Requests月下载量超过**8000万次**,成为最常用第三方
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值