【问题标题】:why did the value of a change? [duplicate]为什么值发生了变化? [复制]
【发布时间】:2020-10-29 10:35:59
【问题描述】:

func_two

def func_two(x):
    x[1][1] = x[2][1]
    x[2][1] = 0 
    return x

a = [[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]]
print(a, ":before function")
b = func_two(a)
print(a, ":after function")
print(b, ":value of b")

这个的输出是

[[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]] :before function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :after function
[[12, 11, 7, 13], [6, 4, 8, 3], [9, 0, 10, 2], [5, 14, 15, 1]] :value of b

为什么“a”的值在函数执行后发生了变化? 如何在不更改函数外部变量的情况下运行 func_two(我没有将任何变量声明为全局变量,这不应该发生)

正常工作的代码 func_one

def func_one(x):
    x = [[3]]
    return x 

a = [[5]]
print(a, ":before function")

b = func_one(a)

print(a, ":after function")
print(b, ":value of b")

这个的输出是

[[5]] :before function
[[5]] :after function
[[3]] :value of b

为什么 func_one 不工作而 func_one 工作?

【问题讨论】:

  • 您期望的隐式副本比 Python 多得多。我推荐阅读nedbatchelder.com/text/names.html——它很好地介绍了 Python 变量和对象的工作原理。
  • 谢谢,@Wups 确实解决了我的问题。
  • 感谢@Monica,--nedbatchelder.com/text/names.html——这是一本很好的读物,我不知道 python 以这种方式处理变量。这实际上解释了我之前遇到的很多错误(我之前已经通过上帝知道如何解决它们(做随机的事情))不知道问题发生的真正原因!!!!非常感谢

标签: python python-3.x list jupyter-notebook


【解决方案1】:

@user2357112 支持 Monica 和 @Wups 在 cmets 中回答了这个问题

回答

import copy

def transition(x):
    y = copy.deepcopy(x)
    y[1][1] = y[2][1]
    y[2][1] = 0 
    return y

a = [[12, 11, 7, 13], [6, 0, 8, 3], [9, 4, 10, 2], [5, 14, 15, 1]]

print(a, ":before function")

b = transition(a)

print(a, ":after function")

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 2018-12-24
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    相关资源
    最近更新 更多