【问题标题】:How can I assign new variable for complex code? [duplicate]如何为复杂代码分配新变量? [复制]
【发布时间】:2020-10-25 16:45:00
【问题描述】:

我想做的是为复杂的代码做一个简单的变量。例如,

list1 = [['apple','banana'], ['cat', 'dog']]
new = list1[0][1]
new = 'bonono'
print(list1[0][1])   # The result is 'banana', but I hope this to be 'bonono'

我不想每次都输入 list1[0][1],我只想输入 new 以获得相同的值。
如果这是 C 语言,也许我可以使用指针,但在 python 中我找不到。
我读过浅拷贝或深拷贝,但似乎两者都不是。所以copy.copy() 也没有用。 谁能告诉我怎么做?

【问题讨论】:

  • 您正在尝试使用“new”作为指针。 Python 没有指针。此外,一旦 new 被赋予一个新值,它就会释放它持有的旧值的别名

标签: python pointers


【解决方案1】:

Python 是一种基于引用的语言,字符串是不可变的,所以当您设置new = 'bonono' 时,您并没有更改同一个对象,而是引用了不同的对象。

你可以这样做:

list1 = [['apple','banana'], ['cat', 'dog']]
new = list1[0][1] = 'bonono'

但您必须确保每次都替换列表条目。

这里有一些更详细的信息来向您展示引用发生了什么:

>>> from sys import getrefcount
>>> list1 = [['apple','banana'], ['cat', 'dog']]
>>> getrefcount('banana')
# One ref in list, one in gc, one in getrefcount call
3
>>> new = list1[0][1]
>>> getrefcount('banana')
# One ref in list, one to new, one in gc, one in getrefcount call
4
>>> new = 'bonono'
>>> getrefcount('banana')
# One ref in list, one in gc, one in getrefcount call
3
>>> getrefcount('bonono')
3
# One ref to new, one in gc, one in getrefcount call

【讨论】:

    【解决方案2】:

    Python 是基于引用的,因此当您将 new 的值设置为其他任何值并且引用不同的对象时,因为字符串是不可变的。而且python没有指针。所以每次更改新值时都可以这样做:

    new,list[0][1] = 'bonno','bonno'
    

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 2017-02-02
      • 2021-09-04
      • 2016-04-26
      • 2015-02-21
      • 2012-10-17
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多