Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在尝试从列表 nm 中删除项目“a”,但不是从列表名称中删除,而是删除函数如何从两个列表中删除它。请帮忙!
我也尝试过使用 del 函数,但没有成功。
>>> name=["a","b","c"] >>> nm=name >>> nm.remove("a") >>> nm`enter code here` ['b', 'c'] >>> name ['b', 'c']
我期待名单最后保持为 ["a","b","c"]。
这是因为name是对列表的引用。nm=name只是创建一个指向同一个列表的新变量。如果您希望它们不同,您需要显式复制列表以便在内存中有两个。
name
nm=name
改变
至
nm=name[:]
这告诉 python 做一个列表的浅拷贝而不是复制引用。有很多方法可以做到这一点,我认为这是最简单的(对于列表),因为它涉及最少的编辑并且没有导入。copy如果您想为其他数据类型实现相同的功能,也可以使用 Python 标准库中的模块。
copy