[英]tqdm progress bar for chained iterables
如果我想在 Python 中組合兩個迭代器,一種方法是使用itertools.chain
。
例如,如果我有兩個范圍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
是 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)
這與其說是答案,不如說是一種解決方法,因為看起來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.