python - Python; 原始列表在函数内发生变化
问题描述
在我的函数中,我需要将列表中元素的值更改为默认值(10)而不更改原始列表。
function(orig_list):
dup_list = list(orig_list)
#Setting the appropriate value for the list but don't want to change the original list.
for i in dup_list:
if dup_list[dup_list.index(i)][1] == 11 or dup_list[dup_list.index(i)][1] == 12 or dup_list[dup_list.index(i)][1] == 13:
dup_list[dup_list.index(i)][1] = 10
但是,当我稍后在代码中调用该函数并打印原始列表时,它也发生了变化。我希望函数执行此操作并给我一个值但不更改原始列表。
解决方案
有多种方法可以复制可变数据结构,例如列表和字典。如果只有不可变的成员,浅拷贝就可以工作,但是如果列表中有一个列表,例如,你需要一个深拷贝。
为了显示:
from copy import deepcopy
l = [1,['a', 'b', 'c'],3,4]
l2 = list(l)
l3 = l.copy()
l4 = deepcopy(l)
# Mutate original list
l[0] = 10 # All of the copies are unaffected by this.
l[1][0] = 'f' # All of the copies except for the deep copy are affected by mutating a mutable item inside the shallow copy of the list.
print(l, l2, l3, l4)
# Result:
# [10, ['f', 'b', 'c'], 3, 4] [1, ['f', 'b', 'c'], 3, 4] [1, ['f', 'b', 'c'], 3, 4] [1, ['a', 'b', 'c'], 3, 4]
推荐阅读
- android - 如何使用已知的屏幕密码自动解锁手机?
- sql-server - 表上的自动索引
- sharepoint-2013 - 使用 CSOM 的 SharePoint Office365 登录问题
- javascript - Artyom.js 立即禁用自身
- haskell - <*> 在 addRecip xy = fmap (+) (recipMay x) <*> recipMay y 中做了什么?
- javascript - CSS文本颜色过渡到多个值
- javascript - 添加范围滑块
- javascript - 404 未找到(webpack 图片)
- python-2.7 - 如何识别用户名和密码字段以使用 Selenium 和 Python 登录 USPS.com
- express - 可以在 Express 中间件中添加路由吗?