python-3.x - 为什么 item2 的值发生了变化?
问题描述
为什么item2
第 20 行之后的值会发生变化?我没有在代码中重新定义任何地方,item2
所以我的期望是它不应该改变。有没有办法在不改变 值的情况下运行相同的代码item2
?这是我的代码:
import random
def one(length):
a = []
for i in range(length):
a.append(1)
return(a)
def two(parent):
b = parent
if random.randint(0,10)<11:
index = random.randint(0,6)
b[index] = 6
return b
item1 = one(6)
print(item1)
item2 = item1
print(item2)
item3 = two(item1)
print(item2)
这是我得到的结果:
[1,1,1,1,1,1]
[1,1,1,1,1,1]
[1,6,1,1,1,1]
解决方案
更改b = parent
为b = parent[:]
第 10 行,@rakesh 提供的答案
推荐阅读
- javascript - 为什么这个 SVG 没有显示在 Google 地图 (JavaScript) 中?
- android - 如何更改导航栏的颜色(手势模式)?
- java - 如何最好地对期望设置 ThrreadLocal 变量的类使用 junit 测试?
- ansible - 我可以浏览 Ansible 的 CICS 资源之间的关系吗?
- python - Python - 将一个 sns.histplot() 中的 bin 用于另一个 / 从 sns.histpllot() 中提取 bin 信息
- php - 在外键约束“followers_ibfk_1”中引用列“follower_id”和引用列“id”不兼容。我的错误是什么?
- python - python中的十六进制到Base64,但我得到错误的结果
- python - 如何使用 matplotlib 制作水平虚线?
- typescript - 下一个 JS Mock API 端点在 req.body 中为 POST 发送参数
- javascript - 将输入转换为十六进制和二进制