python 中有趣的庫tqdm

2021-09-07 20:31:23 字數 2311 閱讀 5054

tqdm 是 python 進度條庫,可以在 python 長迴圈中新增乙個進度提示資訊用法:tqdm(iterator)

# 方法1:

import time

from tqdm import tqdm for i in tqdm(range(100)): time.sleep(0.01) 方法2: import time from tqdm import trange for i in trange(100): time.sleep(0.01)

結果:

0%|          | 0/100 [00:00<?, ?it/s] 11%|█ | 11/100 [00:00<00:00, 100.00it/s] 22%|██▏ | 22/100 [00:00<00:00, 100.00it/s] 32%|███▏ | 32/100 [00:00<00:00, 100.00it/s] 43%|████▎ | 43/100 [00:00<00:00, 100.00it/s] 54%|█████▍ | 54/100 [00:00<00:00, 100.00it/s] 64%|██████▍ | 64/100 [00:00<00:00, 99.11it/s] 74%|███████▍ | 74/100 [00:00<00:00, 99.37it/s] 85%|████████▌ | 85/100 [00:00<00:00, 99.56it/s] 95%|█████████▌| 95/100 [00:00<00:00, 99.69it/s] 100%|██████████| 100/100 [00:01<00:00, 99.70it/s] 

可以為進度條設定描述:

import time

from tqdm import tqdm

pbar = tqdm(["a", "b", "c", "d"]) for char in pbar: # 設定描述 pbar.set_description("processing %s" % char) time.sleep(1)

結果:

0%|          | 0/4 [00:00<?, ?it/s] processing a: 25%|██▌ | 1/4 [00:01<00:03, 1.00it/s] processing b: 50%|█████ | 2/4 [00:02<00:02, 1.00it/s] processing c: 75%|███████▌ | 3/4 [00:03<00:01, 1.00it/s] processing d: 100%|██████████| 4/4 [00:04<00:00, 1.00it/s] 

手動控制進度:

import time

from tqdm import tqdm

# 一共200個,每次更新10,一共更新20次 with tqdm(total=200) as pbar: for i in range(20): pbar.update(10) time.sleep(0.1) #方法2: pbar = tqdm(total=200) for i in range(20): pbar.update(10) time.sleep(0.1) # close() 不要也沒出問題? pbar.close()

結果:

0%|          | 0/200 [00:00<?, ?it/s] 15%|█▌ | 30/200 [00:00<00:01, 150.00it/s] 25%|██▌ | 50/200 [00:00<00:01, 130.43it/s] 30%|███ | 60/200 [00:00<00:01, 119.52it/s] 40%|████ | 80/200 [00:00<00:01, 112.91it/s] 50%|█████ | 100/200 [00:00<00:00, 108.70it/s] 55%|█████▌ | 110/200 [00:01<00:00, 105.93it/s] 65%|██████▌ | 130/200 [00:01<00:00, 104.08it/s] 75%|███████▌ | 150/200 [00:01<00:00, 102.82it/s] 80%|████████ | 160/200 [00:01<00:00, 101.96it/s] 85%|████████▌ | 170/200 [00:01<00:00, 96.38it/s] 90%|█████████ | 180/200 [00:01<00:00, 97.44it/s] 100%|██████████| 200/200 [00:01<00:00, 98.19it/s] 

更多用法,學習完後再補充:

tqdm 顯示進度 Python常用庫 tqdm

tqdm庫比較常用,用於顯示進度條。簡單用法 from tqdm import tqdm for i in tqdm range 2 pass 100 2 2 00 00 00 00,1998.72it s 從上面可以看到生成乙個長度為2的列表傳入tqdm中,在for中迭代,此時輸出了進度條,這裡t...

方法過載中有趣的問題

看到乙個比較有意思的問題 public class invoketest method 1 public static void invoke object obj method 2 public static void invoke int arr method 3 public static v...

語言工程中有趣的事情

如果您閱讀此部落格,您將知道我堅信語言的力量。因此,我當然有很大的偏見,但是我感覺語言工程社群正在增長,並且越來越有趣的東西正在湧現。為此,我認為通過檢視社群中正在發生的事情並列出一些我發現有趣的事情來結束這一年是個好主意。一定 要在聖誕節前 ftomasse samharwell antlr gu...