[英]tqdm progress bar for chained iterables
If I want to combine two iterators in Python, one approach is to use itertools.chain
.如果我想在 Python 中组合两个迭代器,一种方法是使用
itertools.chain
。
For example, if I have two ranges range(50, 100, 10)
and range(95, 101)
, I can get a range [50, 60, 70, 80, 90, 95, 96, 97, 98, 99, 100]
with itertools.chain(range(50, 100, 10), range(95, 101))
.例如,如果我有两个范围
range(50, 100, 10)
和range(95, 101)
,我可以得到一个范围[50, 60, 70, 80, 90, 95, 96, 97, 98, 99, 100]
与itertools.chain(range(50, 100, 10), range(95, 101))
。
tqdm
is an extensible progress bar in Python. tqdm
是 Python 中的可扩展进度条。 However, by default it doesn't seem to be able to count the number of items in a itertools.chain
expression, even when they are fixed.然而,默认情况下它似乎无法计算
itertools.chain
表达式中的项目数,即使它们是固定的。
One solution is to convert the range to a list.一种解决方案是将范围转换为列表。 However this approach doesn't scale.
然而,这种方法不能扩展。
Is there a way to ensure tqdm
understands chained iterators?有没有办法确保
tqdm
理解链式迭代器?
from tqdm import tqdm
import itertools
import time
# shows progress bar
for i in tqdm(range(50, 100, 10)):
time.sleep(1)
# does not know number of items, does not show full progress bar
for i in tqdm(itertools.chain(range(50, 100, 10), range(95, 101))):
time.sleep(1)
# works, but doesn't scale
my_range = [*itertools.chain(range(50, 100, 10), range(95, 101))]
for i in tqdm(my_range):
time.sleep(1)
This is more of a workaround than an answer, because it just looks like tqdm
can't handle it right now.这与其说是答案,不如说是一种解决方法,因为看起来
tqdm
现在无法处理它。 But you can just find the length of the two things you chained together and then include the argument total=
when you call tqdm
.但是你可以找到你链接在一起的两个东西的长度,然后在你调用
tqdm
时包含参数total=
。
from tqdm import tqdm
from itertools import chain
# I started with a list of iterables
iterables = [iterable1, iterable2, ...]
# Get the length of each iterable and then sum them all
total_len = sum([len(i) for i in iterables])
# Then chain them together
main_iterable = chain(*iterables)
# And finally, run it through tqdm
# Make sure to use the `total=` argument
for thing in tqdm(main_iterable, total=total_len):
# Do stuff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.