Python交换值在更改交换顺序时给出了不同的结果
输入:[1,2,3,4]
预期输出:
[2,1,3,4]
给出了预期结果
a = [1,2,3,4]
a[a[0]], a[0] = a[0],a[a[0]]
#Output -> [2, 1, 3, 4]
以下代码在更改交换后, 。订单给出了不正确的输出
a = [1,2,3,4]
a[0],a[a[0]] = a[a[0]],a[0]
# Output -> [2, 2, 1, 4]
,我刚刚切换了作业的顺序。为什么会有所作为?
编辑: 那么,为什么下面的两个案例给出相同的输出:
a = 1 b= 2
a,b = b,a #Case1
b,a = a,b #Case2
print(a,b) #=> prints 2,1 for both
如果问题不够描述,请让我知道我会添加更多评论。 我试图使其尽可能简单。 谢谢
Input:[1,2,3,4]
Expected Output:
[2, 1, 3, 4]
The below code gives the expected result
a = [1,2,3,4]
a[a[0]], a[0] = a[0],a[a[0]]
#Output -> [2, 1, 3, 4]
The below code ie, after changing swapping order gives the incorrect output
a = [1,2,3,4]
a[0],a[a[0]] = a[a[0]],a[0]
# Output -> [2, 2, 1, 4]
I just switched the order of the assignments. Why does that make a difference?
Edit:
Then why do the two cases below give the same output:
a = 1 b= 2
a,b = b,a #Case1
b,a = a,b #Case2
print(a,b) #=> prints 2,1 for both
If the question is not descriptive enough please let me know I will add more comments.
I have tried to make it as simple as possible.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这很重要,因为您基本上执行两个单独的作业。这些作业之一必须首先执行。因此,如果您首先分配
a [0]
,则a [a [0]]
已经可以与a [0] 确定索引。如果您首先分配
a [a [0]]
,则该索引的行为按预期行为,并且之后只有a [0]
更改的值。It matters because you basically perform two separate assignments. One of those assignements has to be performed first. So if you assign
a[0]
first, thena[a[0]]
will already work with the new value ofa[0]
to determine the index. If you first assigna[a[0]]
then the index behaves as expected and only afterwards the value ofa[0]
changes.Python首先评估整个右侧,然后从左到右分配到左侧。在第一种情况下:
在第二种情况下:
请参见 https:https:// docss:// docs .python.org/3/reference/expressions.html#evaluation-order
Python evaluates first the whole right-hand side, then assigns to the left hand side from left to right. In the first case:
In the second case:
See https://docs.python.org/3/reference/expressions.html#evaluation-order
两者都会返回不同的结果,您的代码含义上述
代码返回您的预期结果,但是不正确的结果呢?
解释:
您定义第一个
a [0] = a [a [0]]
与a [0] = a [1](当前值为2)
或在简单的单词中a [0] = 2
。接下来,您调用
a [a [0]] = a [0]
与a [2] = a [0](您已经将A [0]定义为2)< /code>或简单词
a [2] = 2
这为您的结果提供了[2,2,1,4]的结果,
用于交换值时的其他情况
,使用变量的简单案例,并且像常见的交换案例一样工作,但是您使用列表的示例不正确,这更棘手,就像我已经很棘手以前解释过
Both will return different result, your code means like this
Above code return what your expected result, but how about the incorrect one?
Explanation:
You define the first
a[0] = a[a[0]]
which equal witha[0] = a[1] (which current value is 2)
or in simple worda[0] = 2
.Next, you call
a[a[0]] = a[0]
which equal witha[2] = a[0] (you already define a[0] as 2)
or in simple worda[2] = 2
And this give you the result as [2, 2, 1, 4]
For the additional case in swapping value
This's simple case using variable, and work like common swapping case, but your incorrect sample using list, which are more tricky as I already explained before