Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:使用元组重新排列列表的内容_Python_List_Tuples - Fatal编程技术网

python:使用元组重新排列列表的内容

python:使用元组重新排列列表的内容,python,list,tuples,Python,List,Tuples,我是python初学者。最近我看到了这段代码: >>> words = ['I', 'turned', 'off', 'the', 'spectroroute'] >>> words[2], words[3], words[4] = words[3], words[4], words[2] >>> words ['I', 'turned', 'the', 'spectroroute', 'off'] 我对第二行感到困惑。似乎使用了元组,但我

我是python初学者。最近我看到了这段代码:

>>> words = ['I', 'turned', 'off', 'the', 'spectroroute']
>>> words[2], words[3], words[4] = words[3], words[4], words[2]
>>> words
['I', 'turned', 'the', 'spectroroute', 'off']
我对第二行感到困惑。似乎使用了元组,但我不明白为什么列表的顺序会更改为结果

看起来第二行正在这样做:

>>> tmp = words[2]
>>> words[2] = words[3]
>>> words[3] = words[4]
>>> words[4] = tmp
我的问题是:为什么第2行中的代码会因此更改列表


提前谢谢

你说得很对。它在右侧(内存中)创建一个元组,然后将其值解压缩到原始列表中,从而覆盖以前的索引。这就是为什么不需要tmp变量,因为它发生在内存中

它与这个概念相似:

a, b, c = (1, 2, 3)

列表是一种可变的数据结构
words[2]=“foobar”
将列表中的第三个元素更改为
“foobar”
。在

>>> words[2], words[3], words[4] = words[3], words[4], words[2]

首先计算右侧,并将结果字符串分配到列表中的各个位置,从而对其进行更改。

在您选择的Python引用中查找“tuple assignment”。将使用tuple。
字符定义了一个元组,在需要时,元组只是为了清晰和优先。那么这是否意味着它与此类似:单词[0],单词[1],单词[2],单词[3],单词[4]=(单词[2],单词[3],单词[4]=单词[3],单词[4],单词[2])?但是为什么不是这样的:单词[0],单词[1],单词[2],单词[3],单词[4]=(单词[0],单词[1],单词[3],单词[4],单词[2])?你评论中的第一个例子是语法错误,所以它不正确。你的第二个例子在技术上等同于是。但是没有必要将列表的第一个和第二个索引设置为它们的原始值。您仅在不同索引处修改列表中的元素
words
是一个列表容器。它包含5个元素,这些元素可以通过其0-4索引号进行访问和重新分配。还要记住,
words
list对象在整个过程中从未成为任何新对象。只有内容发生了变化。