在while循环中使用tqdm进度条

Ben*_*sse 28 python python-3.x tqdm

我正在制作一个代码模拟一个围绕垄断板的棋子一百万次.我希望有一个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)
Run Code Online (Sandbox Code Playgroud)

Raf*_*azZ 47

您可以tqdm通过total在构造函数中指定参数来使用手动控制.从手册逐字:

pbar = tqdm(total=100)
for i in range(10):
    pbar.update(10)
pbar.close()
Run Code Online (Sandbox Code Playgroud)

为此,您需要知道预期运行的总数.在你的代码中它可能看起来像

...
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()
Run Code Online (Sandbox Code Playgroud)

但是,这段代码并不完美:考虑是否currentData[1]总是小于37 - 进度条将停止而不是更新.如果您尝试在else:...部件中更新它,则可能违反total上限.这是一个开始... :)

  • 为了使上述代码正常工作,您需要`from tqdm import tqdm`或`pbar = tqdm.tqdm(total = 100)`。 (5认同)
  • 请注意,“pbar.update(...)”的参数是进度条的**增量**量,而不是设置的绝对值。 (4认同)
  • 更好的做法是使用 `with tqdm(total=100) as pbar: do... ;pbar.更新(10)` (3认同)

小智 7

由于受到关注,这篇文章很吸引我,我认为最好指出如何通过无限 while 循环来实现这一点。

要在 tqdm 中使用无限循环,您需要使用生成器将 while 循环更改为无限 for 循环。

无限循环(无进度条)

while True:
  # Do stuff here
Run Code Online (Sandbox Code Playgroud)

无限循环(带进度条)

def generator():
  while True:
    yield

for _ in tqdm(generator()):
  # Do stuff here
Run Code Online (Sandbox Code Playgroud)

上面的代码将创建一个与此类似的无限进度条

16it [01:38,  6.18s/it]
Run Code Online (Sandbox Code Playgroud)

请注意,生成器也可以修改为使用条件

def generator():
  while condition:
    yield
Run Code Online (Sandbox Code Playgroud)

  • 这也可以在没有生成器的情况下工作:“progress = tqdm()”,然后在循环内调用“progress.update()”而不带参数。 (5认同)
  • 确实是一个很好的解决方案。 (2认同)