Loop 循环¶
展示循环进度条¶
在运行完后,让进度条消失¶
循环列表的 index 和 value¶
- 用
enumerate
循环字典的 index 和 value¶
- 用
dict.items()
Python
dict = {"x": 1, "y": 2, "z": 3} for key, value in dict.items(): print(key, "corresponds to", value)
逐对循环 pairwise¶
这在循环“当前调仓日”和“下一个调仓日”时非常有用。我在这个视频中学到的,要多用itertools
!
注意
这个方法在某些较低的 Python 版本中可能不适用。
如果 Python 版本低于 3.10,可以使用 more_itertools
:
Python
import more_itertools for a, b in more_itertools.pairwise([1, 2, 3, 4, 5]): print(a, b) # 1 2 # 2 3 # 3 4 # 4 5
rich.Progress
展示进度条¶
可以同时展示多个进度条。
Python
import time from rich.progress import Progress with Progress() as progress: task1 = progress.add_task("[red]Downloading...", total=1000) task2 = progress.add_task("[green]Processing...", total=1000) task3 = progress.add_task("[cyan]Cooking...", total=1000) while not progress.finished: progress.update(task1, advance=0.5) progress.update(task2, advance=0.3) progress.update(task3, advance=0.9) time.sleep(0.02)
遍历某个路径下的所有文件(包括这个路径下的子目录、子子目录等等的所有文件)¶
Python
for root, dirs, files in os.walk(excel_path): for file in files: # 打印 file 的完整相对路径路径,os.path.join 会自动将 root 和 file 之间用反斜杠连接 print(os.path.join(root, file))