簡體   English   中英

在 while 循環中使用 tqdm 進度條

[英]Using tqdm progress bar in a while loop

我正在編寫一個代碼來模擬一個棋子在壟斷板上轉了一百萬次。 我想要一個 tqdm 進度條,每次完成轉盤時都會更新。

以下是我當前的代碼。 我正在使用一個while循環,當電路板的轉數超過所需數量時它會停止。

import os
from openpyxl import Workbook
from monopolyfct import *


def main(runs, fileOutput):

    ### EXCEL SETUP ###
    theWorkbook = Workbook()                              # Creates the workbook interface.
    defaultSheet = theWorkbook.active                     # Creates the used worksheet.
    currentData = ["Current Table Turn", "Current Tile"]  # Makes EXCEL column titles.
    defaultSheet.append(currentData)                      # Appends column titles.

    ### CONTENT SETUP ###
    currentData = [1, 0]             # Sets starting position.
    defaultSheet.append(currentData) # Appends starting position.

    while currentData[0] <= runs:

        ### ROLLING THE DICES PROCESS ###
        dices = twinDiceRoll()
        currentData[1] += dices[2]  # Updating the current tile

        ### SURPASSING THE NUMBER OF TILES ONBOARD ###
        if currentData[1] > 37:   # If more than a table turn is achieved,
            currentData[0] += 1   # One more turn is registered
            currentData[1] -= 38  # Update the tile to one coresponding to a board tile.
        else:
            pass

        ### APPENDING AQUIRED DATA ###
        defaultSheet.append(currentData)

        ### MANAGIING SPECIAL TILES ###
        if currentData[1] == 2 or 15 or 31:   # Community chess
            pass                              #TODO: Make a mechanic simulating the community chest card draw and it's related action.
        elif currentData[1] == 5 or 20 or 34: # Chance
            pass                              #TODO: Make a mechanic simulating the chance card draw and it's related action.
        elif currentData[1] == 28:            # Go to Jail
            pass                              #TODO: Make a mechanic simulating the entire jail process

        ### TWIN DICE ROLL EXCEPTION ###
        if dices[3] is True:  # If the dices roll a double,
            pass              #TODO: Make a mechanic considering that three doubles sends one to Jail.


    ### STORING THE ACCUMULATED DATA ###
    theWorkbook.save(fileOutput)  # Compiles the data in a .xlxs file.


if __name__ == "__main__":
    terminalWidth = os.get_terminal_size().columns                                               # Gets current terminal width.
    space(3)
    print("Python Monopoly Statistics Renderer".upper().center(terminalWidth))                   # Prints the title.
    print("(PMSR)".center(terminalWidth))                                                        # Prints the acronym.
    space(2)
    runs = int(request("For how many table turns do you want the simulation to run?"))           # Prompts for the desired run ammount
    #runs = 1000
    fileOutput = request("What should be the name of the file in which statistics are stored?")  # Prompts for the desired store filename
    #fileOutput = "test"
    fileOutput += ".xlsx"                                                                        # Adds file extension to filename
    main(runs, fileOutput)

您可以通過在構造函數中指定total參數來在tqdm使用手動控制。 手冊中的逐字逐句:

with tqdm(total=100) as pbar:
    for i in range(10):
        sleep(0.1)
        pbar.update(10)

更新

要在沒有上下文管理器(又名with語句)的情況下手動控制tqdm ,您需要在使用完成后關閉進度條。 這是手冊中的另一個示例:

pbar = tqdm(total=100)
for i in range(10):
    sleep(0.1)
    pbar.update(10)
pbar.close()

為此,您需要知道預期運行的總數。 在您的代碼中,它可能看起來像

...
pbar = tqdm(total = runs+1)
while currentData[0] <= runs:

    ### ROLLING THE DICES PROCESS ###
    dices = twinDiceRoll()
    currentData[1] += dices[2]  # Updating the current tile

    ### SURPASSING THE NUMBER OF TILES ONBOARD ###
    if currentData[1] > 37:   # If more than a table turn is achieved,
        currentData[0] += 1   # One more turn is registered
        currentData[1] -= 38  # Update the tile to one coresponding to a board tile.
        pbar.update(1)
    else:
        pass
...
pbar.close()

然而,這段代碼並不完美:考慮currentData[1]是否總是小於currentData[1]進度條只會停止而不更新。 如果您嘗試在else:...部分更新它,您可能會違反total上限。 這是一個開始 :)

由於受到關注,這篇文章很吸引我,我認為最好指出如何通過無限 while 循環來實現這一點。

要在 tqdm 中使用無限循環,您需要使用生成器將 while 循環更改為無限 for 循環。

無限循環(無進度條)

while True:
  # Do stuff here

無限循環(帶進度條)

def generator():
  while True:
    yield

for _ in tqdm(generator()):
  # Do stuff here

上面的代碼將創建一個與此類似的無限進度條

16it [01:38,  6.18s/it]

請注意,生成器也可以修改為使用條件

def generator():
  while condition:
    yield

user12128336 的答案的附加版本。

您可以在生成器中執行所有迭代操作。 只需在迭代結束時添加yield

from tqdm.auto import tqdm
from time import sleep


def generator():
    while True:
        sleep(0.3) # iteration stuff
        yield
        
for _ in tqdm(generator()): pass

# 77it [00:23,  3.25it/s]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM