python - 在 while 循环中使用 tqdm 进度条

标签 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)

最佳答案

您可以通过在构造函数中指定 total 参数来在 tqdm 中使用手动控制。来自 manual 的逐字记录:

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

更新

要在没有上下文管理器的情况下手动控制 tqdm(又名 with 语句),您需要在完成使用后关闭进度条。这是手册中的另一个示例:

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] 是否总是小于 37 —— 进度条将停止而不更新。如果您尝试在 else:... 部分更新它,您可能会违反 total 上限。这是一个开始 :)

关于python - 在 while 循环中使用 tqdm 进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808140/

相关文章:

python - 如何使用 tqdm 遍历列表

Python 进度条 tqdm

python - 是否可以在不超过最大递归深度的情况下在 python 中使用参数 m>=4 和 n>=1 计算递归 ackermann(m,n) 函数?

python - 为什么 pygame 键码是特定于操作系统的?

python - 在集合字典中识别包含正确值的集合

python - 双重迭代到列表python 3

python-3.x - 即使没有应用前向传播,也会调整 nn.ModuleList() 的权重

python - 使用多个条

python - 无法添加列表成员

python - 在 python 上求解复杂的隐式方程