Python列表不反映变量更改 [英] Python list doesn't reflect variable change

查看:111
本文介绍了Python列表不反映变量更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编写此代码时:

polly = "alive"
palin = ["parrot", polly]
print(palin)
polly = "dead"
print(palin)

我认为它将输出以下内容:

I thought it would output this:

"['parrot', 'alive']"
"['parrot', 'dead']"

但是,事实并非如此.我如何获得它来输出呢?

However, it doesn't. How do I get it to output that?

推荐答案

Python变量保存对的引用.因此,在定义palin列表时,您传入的是polly引用的值,而不是变量本身.

Python variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.

您应该将值想象为气球,变量是绑定到那些气球的线程. "alive"是一个气球,polly只是该气球的一个线程,并且palin列表具有与同一气球绑定的不同线程.在python中,列表只是一系列线程,所有线程均从0开始编号.

You should imagine values as balloons, with variables being threads tied to those balloons. "alive" is a balloon, polly is just a thread to that balloon, and the palin list has a different thread tied to that same balloon. In python, a list is simply a series of threads, all numbered starting at 0.

下一步是将polly字符串绑定到新的气球"dead",但是列表仍然保留与"alive"气球相关的旧线程.

What you do next is tie the polly string to a new balloon "dead", but the list is still holding on to the old thread tied to the "alive" balloon.

您可以通过按索引重新分配列表以引用每个线程来将该线程替换为列表所包含的"alive";在您的示例中,线程为1:

You can replace that thread to "alive" held by the list by reassigning the list by index to refer to each thread; in your example that's thread 1:

>>> palin[1] = polly
>>> palin
['parrot', 'dead']

在这里,我只是将palin[1]线程绑定到了polly所绑定的相同对象上,无论可能是什么.

Here I simply tied the palin[1] thread to the same thing polly is tied to, whatever that might be.

请注意,python中的任何集合(例如dictsettuple等)也只是线程的集合.其中一些可以将其线程换成不同的线程,例如列表和字典,这就是使python中的某些东西可变"的原因.

Note that any collection in python, such as dict, set, tuple, etc. are simply collections of threads too. Some of these can have their threads swapped out for different threads, such as lists and dicts, and that's what makes something in python "mutable".

字符串是可变的,不是.一旦定义了像"dead""alive"这样的字符串,它就是 one 气球.您可以将其与线程(变量,列表或其他任何东西)绑定在一起,但是不能替换其中的字母.您只能将该线程绑定到完全 new 字符串.

Strings on the other hand, are not mutable. Once you define a string like "dead" or "alive", it's one balloon. You can tie it down with a thread (a variable, a list, or whatever), but you cannot replace letters inside of it. You can only tie that thread to a completely new string.

Python中的大多数功能都可以像气球一样.整数,字符串,列表,函数,实例,类都可以绑定到一个变量中,也可以绑定到一个容器中.

Most things in python can act like balloons. Integers, strings, lists, functions, instances, classes, all can be tied down to a variable, or tied into a container.

您可能还想阅读内德·巴切尔德(Ned Batchelder)关于Python名称的论文.

这篇关于Python列表不反映变量更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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