如何在Python的tqdm模块中格式化大数字以提升可读性?
在tqdm中格式化大数字为千分位形式
当然可以实现,你可以通过自定义格式化函数结合tqdm的参数配置,直接将大数字显示为带千分位分隔符的形式,完全替代unit_scale的单位转换逻辑。
实现步骤
- 先写一个简单的千分位格式化函数:
def thousand_sep(num): return f"{num:,}"
- 结合tqdm的参数实现自定义显示:
from tqdm import tqdm import time def thousand_sep(num): return f"{num:,}" # 模拟处理1,500,000行数据 total_rows = 1500000 with tqdm(total=total_rows, n_fmt=lambda x: thousand_sep(int(x)), # 格式化已完成数量 total_fmt=lambda x: thousand_sep(int(x)), # 格式化总数量 unit="row") as pbar: for _ in range(100): time.sleep(0.01) pbar.update(15000) # 每次更新15,000行 # 获取当前处理速率并格式化 current_rate = pbar.format_dict.get("rate") if current_rate: pbar.set_postfix({"处理速率": f"{thousand_sep(int(current_rate))} rows/s"})
效果说明
运行后进度条会显示类似这样的内容:500,000/1,500,000 [00:01<00:02, 处理速率: 150,000 rows/s]
完全符合你想要的千分位分隔显示需求,不会出现M/K这类单位缩写。
更灵活的自定义格式(可选)
如果需要更复杂的进度条布局,可以直接自定义bar_format模板:
from tqdm import tqdm import time def thousand_sep(num): return f"{num:,}" total = 1000000 bar_template = "{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]" with tqdm(total=total, unit="row") as pbar: while pbar.n < total: time.sleep(0.01) pbar.update(10000) # 格式化各个关键数值 n_fmt = thousand_sep(pbar.n) total_fmt = thousand_sep(pbar.total) current_rate = pbar.format_dict.get("rate", 0) rate_fmt = f"{thousand_sep(int(current_rate))} rows/s" if current_rate else "0 rows/s" # 更新进度条格式 pbar.bar_format = bar_template.format(n_fmt=n_fmt, total_fmt=total_fmt, rate_fmt=rate_fmt, **pbar.format_dict)
内容的提问来源于stack exchange,提问作者Stanislav
相关产品推荐
相关产品推荐

