在 Python 中追加与重新定义变量 [英] Append vs. redefining variable in Python

查看:31
本文介绍了在 Python 中追加与重新定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这个问题在其他地方得到了回答,首先让我以道歉作为我的问题的开头.我查看了Stack Overflow 建议的一些问题,但没有一个包含我正在寻找的答案.我还对为什么发生这种情况更感兴趣,而不是任何避免该问题的解决方法.我尝试回答我自己的问题,但我只能将问题简化为一个更简单的问题.无论如何,有人可以帮我理解下面两组代码之间的区别,这样我才能理解不同输出的原因吗?

First let me preface my question with an apology if this has been answered somewhere else. I reviewed a few of the questions Stack Overflow suggested, but none of them contained the answer I'm looking for. I am also more interested in why this is happening than any workarounds to avoid the problem. I tried answering my own question, but I was only able to reduce the problem to a simpler one. Anyway, can someone please help me understand the difference between the two sets of code below that way I can understand the reasoning for the different outputs?

版本 1(在变量 dog 上使用附加):

Version 1 (using append on the variable dog):

cat = [ ]
dog = [ ]
dog.append(1)
print dog # [1]
print cat # [ ]        
cat.append(dog)        
print dog # [1]
print cat # [ [1] ]
dog.append(1)
print dog # [1, 1]
print cat # [ [1, 1] ]        
dog.append(1)        
print dog # [1, 1, 1]        
print cat # [ [1, 1, 1] ]
cat.append(dog)        
print dog # [1, 1, 1]
print cat # [ [1, 1, 1], [1, 1, 1] ]

版本 2(将 dog 重新定义为不同的列表):

Version 2 (redefining dog as a different list):

cat = [ ]
dog = [ ]
dog = [1]
print dog # [1]
print cat # [ ]
cat.append(dog)
print dog # [1]
print cat # [ [1] ]
dog = [1, 1]
print dog # [1, 1]
print cat # [ [1] ]
dog = [1, 1, 1]
print dog # [1, 1, 1]
print cat # [ [1] ]
cat.append(dog)
print dog # [1, 1, 1]
print cat # [ [1], [1, 1, 1] ]

我对 Python 中 append 方法的天真理解使我期望版本 1 具有与版本 2 相同的输出.我不明白为什么附加 dog 会影响变量 cat 以任何方式进行,除非我通过附加或其他方式明确更改了 cat.

My naïve understanding of the append method in Python led me to expect Version 1 to have the same output as Version 2. I don't understand why appending dog would affect the variable cat in any way unless I explicitly changed cat via append or some other way.

推荐答案

这是许多编程语言的功能,而不仅仅是 Python.这通常称为通过引用传递(google it).

This is a feature of many programming languages, not just python. This is more generally called passing by reference (google it).

在 Python 中,可变数据结构通常通过引用传递(例如列表/字典等),而不可变数据结构(例如元组/字符串/整数)作为副本传递.所以在代码片段#1 中,当你第一次执行 cat.append(dog) 时, cat 现在有一个对狗列表的引用.(如果您来自 C++/C 背景,我可以松散地"将其与指针的概念进行比较:不是 C++ 也有引用,所以我松散地说......).

In Python, mutable data-structures are generally passed by reference (such as list/dict etc) while immutable data-structures (such as tuples/strings/ints) are passed as copies. So in code snippet #1, when you do cat.append(dog) the first time around, cat now has a reference to the dog list. (if you are from a C++/C background, I can "loosely" compare this to the concept of pointers: not c++ has reference too, so i say loosely...).

如果还是复杂的话,想想catdog的地址".如果dog发生变化,cat也会有同样的变化.

If its still complicated, think of cathaving the "address" of dog. If dog changes, cat will have the same changes.

来到你的代码片段#2...

Coming to your code snippet #2...

当您重新定义 dog 时,您实际上是在使 dog 指向一个完全不同的列表.所以 [1,1][1] 是两个完全不同的列表.

When you redefine dog, you are essentially making dog point to a different list altogether. so [1,1] and [1] are two different lists completely.

为了进一步阐明这个概念(mutable vs immutable),尝试一个稍微不同的练习......

To clarify this concept further (of mutable v/s immutable), try a slightly different exercise...

def func_mutable(dog):
    dog.append(1)

def func_immutable(strng):
    strng+="1"

dog = []
print dog #prints []
func_mutable(dog)
print dog #prints [1]

strng = "1"
print strng #prints "1"
func_immutable(strng)
print strng #still prints "1", and not "11"

dog 在函数调用后发生变化,因为列表保存了引用,并且对引用所做的所有更改都反映在 dog(即函数的被调用者)中.strng 不会改变,b/c 当func_immutable 做strng+="1" 时,它实际上是对传入的参数strng 进行复制,然后对其进行修改.该修改是对 local 变量 strng 进行的,如果不返回则丢失(如我的代码中的情况)

dog changes after the function call because the list holds the reference and all changes made to the reference are reflected in the dog(i.e. the callee of the function). strng does not change, b/c when func_immutable does strng+="1", its actually making a copy of the passed parameter strng, and then modifying it. That modification is made to the local variable strng and lost if not returned(as is the case in my code)

这篇关于在 Python 中追加与重新定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆