首页 > 解决方案 > 为什么 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]

标签: python-3.xfunctionrandom

解决方案


更改b = parentb = parent[:] 第 10 行,@rakesh 提供的答案


推荐阅读