[英]Python list.remove() removes items from another list
我要刪除文件夾名稱中包含“完成”的文件夾。 這是我的代碼
import os
mainPath = os.getcwd() + "/MyFolder/"
folderList = os.listdir(mainPath)
tempList = folderList # so that I can iterate while using remove()
print len(tempList)
print len(folderList)
for folder in tempList:
if 'Done' in folder:
folderList.remove(folder)
print len(tempList) # expected: Not to change
print len(folderList)
我得到的輸出是:
26
26
22
22
我不明白為什么它要從testList中刪除項目。 它不應該只從folderList刪除嗎?
您使列表指向同一件事。 使用copy.deepcopy
本質上,當您執行tempList = folderList
它會使兩個列表指向同一件事。 如果您希望可以分別處理同一列表的兩個副本,則需要執行以下操作:
import copy
tempList = copy.deepcopy(folderList)
如果您知道列表中的所有項目都是不可變的,則可以執行tempList = folderList[:]
,但是deepcopy
更安全。
有關此相關問題的信息很多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.