上次迭代后的 tqdm 更新 [英] tqdm update after last iteration

查看:115
本文介绍了上次迭代后的 tqdm 更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 tqdm 作为一个不错的进度条,但在迭代进度条后我想更新描述.

I'm using tqdm as a nice progressbar, but after iterating over the progressbar I want to update the description.

下面是一个简单的例子:

The following is a simple example:

with tqdm(somelist) as pbar:
  for element in pbar:
    foo(element)

  pbar.set_description('We finished')

我得到输出:

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

但预期:

We finished: 100%|███████████████████████████| 10/10 [00:00<00:00, 239674.51it/s]

我已经尝试将 pbar.update()pbar.refresh()refresh=True 作为 的参数set_description,都没有用.

I've tried pbar.update(), pbar.refresh() and refresh=True as a parameter for set_description, neither worked.

当然,您可以随时打印或使用 tqdm.write(),但除了进度条外,它会更整洁.

Of course, one can always print or use tqdm.write(), but would be neater to have besides the progress bar.

推荐答案

您是否尝试过下面的代码?您可以使用 if 条件 if element == somelist[-1] 检查当前 element 是否是 some list 中的最后一项.如果 elementsomelist 中的最后一项,那么您知道它将在此之后完成,因此您可以更新 pbar 描述

Have you tried this code below? You can check if the current element is the last item in some list by using the if condition if element == somelist[-1]. If the element is the last item in somelist, then you know it will be finished after this so you can update the pbar description

with tqdm(somelist) as pbar:
  for element in pbar:
    foo(element)
    if element == somelist[-1]:
        # Update when element is the last item in some list
        pbar.set_description("We finished")

另一种方法是使用递增的 i 变量来检查它是在迭代结束还是现在

Another way is to use an increasing i variable to check if it is at the end of the iteration or now

i = 0
with tqdm(somelist) as pbar:
  for element in pbar:
    foo(element)
    i += 1
    if i == len(somelist):
        # Update when element is the last item in some list
        pbar.set_description("We finished")

这篇关于上次迭代后的 tqdm 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆