为什么其他列表也会改变?

时间:2015-11-01 19:58:10

标签: python python-2.7 dictionary

我已经解决了Project Euler的问题5(从1到20的所有数字中,可以被完全整除的最小正数是多少(没有余数?),但是我想找到一种更快的方法(目前0.000109195709229秒)。

我尝试了一种动态方法,但是当我运行下面的代码时(它只是第一部分)我不明白为什么 d [var] [counter] 如果我明确地得到+1写了 d [i] [counter] + = 1

n = 20
d = {1:[0,1] + [0]*19}  #a dictionary that assigns to each number a list of its prime factorization
for i in xrange(2,3):   #I changed n+1 with 3 for simplicity
    var = i
    counter = 2
    notDone = True
    while notDone:
        if var % counter == 0:
            var /= counter
            print var, d[var]
            d[i] = d[var]           #i has the same prime factorization of var ...
            print var, d[var]
            d[i][counter] += 1      #... except for 1 number (counter)
            print var, d[var]        #wtf?
            notDone = False
        else:
            counter += 2 if counter != 2 else 1

这是结果:

1 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1 [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

为什么会这样?

1 个答案:

答案 0 :(得分:1)

d[i] = d[var]

变量d[i]将保留与d[var]相同的列表对象,因为列表 mutable

相反,您需要d[var]副本,您可以获得由

d[i] = d[var][:]