我想比較從文件中讀取的禁止文件夾列表。但是,我們必須檢查任務是否具有文件夾的父ID,然後檢查該文件夾是否與禁止的文件夾匹配。我正在循環的列表可以包含許多項目。Python中嵌套`for`循環的替代方法
for task in tasks:
#Check the task is on their timesheet
if task["id"] == entry["item_id"]:
for folder in folders:
#See if the task is inside the folder
if task["parent_id"] == folder["id"]:
for forbiddenFolder in forbiddenFolders:
#If the folder is on the list
if forbiddenFolder == folder["name"]:
body_of_email +=("Using a task within a folder that is not permiited " + forbiddenFolder + "\r\n")
folder["name"]
break
此代碼使用三個嵌套for
循環,這可能會很慢。我可以提高效率嗎?
當你迭代大量東西時,嵌套循環通常只是一個問題 - 在這種情況下,你基本上是在尋找一條路徑,所以它不是非常低效,因爲在大多數情況下,你會提前失敗。 –
歡迎來到SO!我把你的問題稍微修改了一下 - 在每個問題結束時,沒有必要說「提前致謝」。 –