Python:使用函数调用,为什么列表会自动更改?

时间:2016-07-12 22:26:26

标签: python list python-3.x

我是Python的新手并试图解决Codechef问题。我遇到了这个问题。 https://www.codechef.com/ZCOPRAC/problems/ZCO14001。 当我试图解决相同问题时,我的答案与测试用例答案不符。我试图找出我的错误并观察到当函数 three()被调用时 x [Position] 被更改但这也改变了我的列表y 。有人可以解释为什么 list y 正在改变吗?

测试案例是:
7 4
3 1 2 1 4 0 1
3 2 2 2 2 4 1 3 1 4 0

预期产量:
2 1 3 1 4 0 1

def Game():
    # Width, Max height
    a = input("")
    Width, Height = a.split()
    # Initial Heights
    x = input("")
    x = x.split()
    x = [ int(d) for d in x ]
    y=x
    print("Initial",y)
    # Commands
    Command = input("")
    Command = Command.split()
    # Hook position
    Position=0
    # Quit
    def zero():
        quit()
    #Move Left
    def one():
        nonlocal Position
        if Position == 0:
            pass
        else:
            Position=Position-1
    # Move Right
    def two():
        nonlocal Position
        if Position == (int(Width) - 1):
            pass
        else:
            Position = Position + 1
    # Pickup box
    def three():
        nonlocal x
        if x==y:
            x[Position]=x[Position]-1 
        # Box is picked up
        else:
            pass
        print("At leaving:",y)
    # Drop box
    def four():
        nonlocal x,y
        if x!=y and x[Position]!=Height:
            x[Position] = x[Position] + 1
            y=x
        else:
            pass
    # Executing commands
    for c in range(0, len(Command)):
        if Command[c] == '1':
            one()
        elif Command[c] == '2':
            two()
        elif Command[c] == '3':
            print("Before entering:",y)
            three()
        elif Command[c] == '4':
            four()
        else:
            zero()
    print("Result",y)
Game()

1 个答案:

答案 0 :(得分:0)

看看你的作业:

y=x

它们是相同的列表 - y不是x的副本,它是对同一数据的另一个引用。如果您需要它们作为单独的副本,请尝试

y = list(x)