【问题标题】:variable gets redefined inside a python function without explicitly changing it [duplicate]变量在没有显式更改的情况下在 python 函数中重新定义[重复]
【发布时间】:2020-04-28 08:35:47
【问题描述】:
   def f():
        list_0 = [1,2,3,4]
        p = [0,1,2,3,4,5,6,7,8]
        for i in list_0:
            x = p
            x[i] ="L"
            print(x)
            print(p)
    f()

希望结果是: 0,"L",2,3,4,5,6,7,8 , 0,1,"L",3,4……等等, 但是得到了, 0,"L",2,3,4,5,6,7,8 , 0,"L","L",3,4,5,6,7,8.. 所以一,“L”被保存了 .如何更改代码以使变量 p 不变并保持不变

【问题讨论】:

  • x = p 使 x 和 p 指向 相同的对象变量没有被重新定义,你只是在改变同一个对象,被两个不同的变量引用。
  • 问题的发生只是因为x 被分配给同一个p。所以,当x 改变时,p 也会改变。要解决这个问题,您需要从p 创建一个副本,如下所示:x = p.copy()
  • 阅读以下内容:nedbatchelder.com/text/names.html

标签: python function variables


【解决方案1】:

这样写你的代码:-

def f():
    list_0 = [1,2,3,4]
    p = [0,1,2,3,4,5,6,7,8]
    for i in list_0:
        x = p.copy()
        x[i] ="L"
        print(x)
        print(p)
f()

【讨论】:

  • 不需要import copylist 对象(和大多数内置容器)有.copy() 方法
  • 你甚至不需要copy模块,因为list已经有一个名为copy()的方法你需要使用这个x = p.copy()
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
  • 2014-01-10
相关资源
最近更新 更多