链式可迭代对象的tqdm进度条

3
如果我想在Python中合并两个迭代器,其中一种方法是使用itertools.chain
例如,如果我有两个范围range(50, 100, 10)range(95, 101),我可以用itertools.chain(range(50, 100, 10), range(95, 101))得到一个范围[50, 60, 70, 80, 90, 95, 96, 97, 98, 99, 100]tqdm是Python中的一个可扩展进度条。但是,默认情况下,即使迭代器已经固定,它似乎也无法计算itertools.chain表达式中的项目数。
一种解决方案是将范围转换为列表。但是这种方法无法扩展。
有没有办法确保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)
2个回答

4
截至2023年,使用tqdm库中的itertools可以更简便地实现。
import numpy as np    
from tqdm.contrib.itertools import product

a, b = np.arange(1,10,1), np.arange(20,30,1)

for a1, b1 in product(a,b):
    print(a1, b1)

1
这更像是一种变通方法而不是答案,因为看起来 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接