我想将当前项目(字符串表示)添加到tqdm进度条中。
这是没有任何额外文本的代码(非常简短和简洁):
from tqdm import tqdm
import time
animals = ["cat", "dog", "bird", "fish", "insect"]
for animal in tqdm(animals):
time.sleep(1)
80%|████████ | 4/5 [00:04<00:01, 1.14s/it]
以下是展示正在处理的项(这里是动物名称)的两种方法:
progress = tqdm(animals)
for animal in progress:
progress.set_postfix_str(animal)
time.sleep(1)
40%|████ | 2/5 [00:02<00:04, 1.46s/it, bird]
和
with tqdm(total=len(animals)) as progress:
for animal in animals:
progress.set_postfix_str(animal)
time.sleep(1)
progress.update()
60%|██████ | 3/5 [00:03<00:02, 1.04s/it, fish]
这两种方法都需要添加相当多的额外代码并需要指定进度条对象。我没有找到更简单的方法来实现这一点。我是否错过了tqdm提供的某些功能?
特别是,我一直在寻找一种告诉tqdm输出其迭代器返回项的字符串(使用例如__str __()
)的方法。
for animal in tqdm(animals, postfix="{item}") # Note: does not work!
time.sleep(1)