如果你有一个进度条,那么你需要能够预测数据结构的长度。
range
实现了 hook 方法 __len__
,所以你可以使用内置函数 len
来获取长度。
>>> dir(range(10))
[ '__le__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index', 'start', 'step', 'stop']
>>> len(range(10))
10
< p > < code > zip ,然而,它没有提供一种猜测包装结构长度的方法,所以可能这就是为什么
tqdm
不能显示进度条的原因。
dir(zip(range(10)))
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> len(zip(range(10)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'zip' has no len()
编辑:
没错,就是这样。看看文档。
...
Wrapping enumerated iterables: use enumerate(tqdm(...))
instead of
tqdm(enumerate(...))
. The same applies to numpy.ndenumerate
. This is
because enumerate
functions tend to hide the length of iterables. tqdm
does not.
...
Manual control on tqdm()
updates by using a with
statement:
with tqdm(total=100) as pbar:
for i in range(10):
pbar.update(10)
If the optional variable total (or an iterable with len()
) is
provided, predictive stats are displayed.
with
is also optional (you can just assign tqdm()
to a variable, but
in this case don't forget to del
or close()
at the end:
pbar = tqdm(total=100)
for i in range(10):
pbar.update(10)
pbar.close()
list = [numbers, letters]
并通过longest = list[sorted([(i,len(l)) for i,l in enumerate(list)], key=lambda t: t[1])[-1][0]]
获取最大的列表,然后简单地放置total=len(longest)
。这种方法也适用于itertools.zip_longest
。 - Muneeb Ahmad Khurram