简体   繁体   English

为什么在进入for循环后立即将p [1]的值设为'0'?

[英]Why is the value of p[1] is '0' immediately after entering the for loop?

The python function is here: python函数在这里:

def rot(p):
    q = p

    print "P val: ", p, "len(p): ", len(p)
    for i in range(len(p)):
        if (i == (len(p)-1)):
            q[0] = p[i]
            print "P val if: ", p, "p(i) : " , p[i]

        else:
            q[i+1] = p[i]
            print "P val else: ", p, "p(i) : " , p[i]


    return q

And the output is here: 输出在这里:

P val:  [0, 1, 0, 0, 0] len(p):  5
P val else:  [0, 0, 0, 0, 0] p(i) :  0
P val else:  [0, 0, 0, 0, 0] p(i) :  0
P val else:  [0, 0, 0, 0, 0] p(i) :  0
P val else:  [0, 0, 0, 0, 0] p(i) :  0
P val if:  [0, 0, 0, 0, 0] p(i) :  0

*The question is, why is the list p changing its p[1] value to 0 after entering the for loop?? *问题是,为什么列表p在进入for循环后将其p [1]的值更改为0? * *

Because q and p reference the same list. 因为qp引用相同的列表。 Thus any change made to the list through variable q will also be reflected in variable p because both represent the same underlying list. 因此,通过变量q对列表所做的任何更改也将反映在变量p因为它们都表示相同的基础列表。 For example: 例如:

>>> p = [1, 2, 3]
>>> q = p
>>> q
[1, 2, 3]
>>> q[0] = 0
>>> q
[0, 2, 3]
>>> p
[0, 2, 3]

This shows that updates made through q are also visible in p . 这表明通过q进行的更新在p中也可见。 This is because p and q are bound to the same list variable: 这是因为pq绑定到相同的列表变量:

>>> p is q
True

To fix it 要解决这个问题

Work on a copy of p using slice notation: 使用切片符号处理p副本

def rot(p):
    q = p[:]    # copy p
    ...         # rest of your function...


>>> l = [0, 1, 0, 0, 0]
>>> rot(l)
P val:  [0, 1, 0, 0, 0] len(p):  5
P val else:  [0, 1, 0, 0, 0] p(i) :  0
P val else:  [0, 1, 0, 0, 0] p(i) :  1
P val else:  [0, 1, 0, 0, 0] p(i) :  0
P val else:  [0, 1, 0, 0, 0] p(i) :  0
P val if:  [0, 1, 0, 0, 0] p(i) :  0
[0, 0, 1, 0, 0]
>>> l
[0, 1, 0, 0, 0]

l is unchanged. l不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM