[英]Python list.remove() removes items from another list
I want to remove the folders containing 'Done' in the folder name. 我要删除文件夹名称中包含“完成”的文件夹。 Here is my code
这是我的代码
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)
The output I get is: 我得到的输出是:
26 26
26 26
22 22
22 22
I do not understand why it is deleting items from testList . 我不明白为什么它要从testList中删除项目。 Shouldn't it delete only from folderList ?
它不应该只从folderList删除吗?
You're making the lists point to the same thing. 您使列表指向同一件事。 use
copy.deepcopy
使用
copy.deepcopy
Essentially when you do tempList = folderList
it makes the two lists point to the same thing. 本质上,当您执行
tempList = folderList
它会使两个列表指向同一件事。 If you want two copies of the same list that you can operate on separately you need to do: 如果您希望可以分别处理同一列表的两个副本,则需要执行以下操作:
import copy
tempList = copy.deepcopy(folderList)
If you know that all the items in your list are immutable, you can do tempList = folderList[:]
, but deepcopy
is safer. 如果您知道列表中的所有项目都是不可变的,则可以执行
tempList = folderList[:]
,但是deepcopy
更安全。
There's a wealth of information on this related question 有关此相关问题的信息很多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.