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

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

问题描述

当我写这段代码时:

polly = "活着"佩林 = [鹦鹉",波莉]打印(佩林)波利=死了"打印(佩林)

我认为它会输出这个:

"['鹦鹉', '活着']"['鹦鹉','死']"

然而,事实并非如此.我如何让它输出那个?

解决方案

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

您应该将值想象为气球,变量是与这些气球相关联的线程."alive" 是一个气球,polly 只是那个气球的一个线程,palin 列表有一个不同的 系在同一个气球上的线.在 Python 中,列表只是一系列线程,所有线程都从 0 开始编号.

接下来要做的是将 polly 字符串绑定到一个新的气球 "dead",但列表仍然保留着绑定到 活着"气球.

您可以将该线程替换为列表所持有的"alive",方法是通过索引重新分配列表以引用每个线程;在您的示例中,线程 1:

<预><代码>>>>佩林[1] = 波莉>>>佩林['鹦鹉','死']

在这里,我只是将 palin[1] 线程绑定到与 polly 绑定的同一事物上,无论它是什么.

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

另一方面,字符串不是可变的.一旦你定义了一个像 "dead""alive" 这样的字符串,它就是一个 one 气球.你可以用一个线程(一个变量、一个列表或其他什么)把它绑起来,但你不能替换它里面的字母.您只能将该线程绑定到一个全新的字符串.

python 中的大多数东西都可以像气球一样工作.整数、字符串、列表、函数、实例、类,都可以绑定到一个变量,或者绑定到一个容器中.

您可能还想阅读 Ned Batchelder 关于 Python 名称的论文.

When I write this code:

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 variables hold references to values. Thus, when you define the palin list, you pass in the value referenced by polly, not the variable itself.

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.

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.

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']

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

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".

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.

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.

You may want to read Ned Batchelder's treatise on Python names too.

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

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