Python 在while循环中使用tqdm进度条
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45808140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using tqdm progress bar in a while loop
提问by Benjamin Chausse
I am making a code that simulates a pawn going around a monopoly board a million times. I would like to have a tqdm progress bar that is updated every time a turn around the board is achieved.
我正在编写一个代码,模拟一个棋子在垄断板上走一百万次。我想有一个 tqdm 进度条,每次完成转板时都会更新。
Below is my current code.I am using a while loop which stops when the number of turns around the board surpasses the desired number.
下面是我目前的代码。我正在使用 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)
回答by RafazZ
You can use manual control in tqdm
by specifying a total
argument in the constructor. Verbatim from the manual:
您可以tqdm
通过total
在构造函数中指定参数来使用手动控制。手册中的逐字逐句:
from tqdm import tqdm
pbar = tqdm(total=100)
for i in range(10):
pbar.update(10)
pbar.close()
For this to work you need to know the total number of expected runs. In your code it could look something like
为此,您需要知道预期运行的总数。在您的代码中,它可能看起来像
...
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()
However, this code isn't perfect: consider if the currentData[1]
is always less than 37 -- the progress bar will just stop and not update. If you try to update it in the else:...
part, you might violate the total
upper bound. This is a start tho :)
然而,这段代码并不完美:考虑是否currentData[1]
总是小于 37——进度条只会停止而不更新。如果您尝试在else:...
零件中更新它,则可能会违反total
上限。这是一个开始 :)