Python 3.x 为什么item2的值发生了变化?
为什么第20行之后,Python 3.x 为什么item2的值发生了变化?,python-3.x,function,random,Python 3.x,Function,Random,为什么第20行之后,item2的值发生了变化?在代码中没有我重新定义的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
item2
的值发生了变化?在代码中没有我重新定义的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)
更改
b=parent
tob=parent[:]
在第10行,
@rakesh提供的答案应该会有所帮助。要修复此问题,请使用
b=parent[:]
如果是随机的。randint(0,10)@Rakesh b=parent[:]工作起来非常感谢这工作做得很好,但仍然不明白为什么(无论如何它完成了工作)
[1,1,1,1,1,1]
[1,1,1,1,1,1]
[1,6,1,1,1,1]