简体   繁体   English

Python:为什么交换最大和最小数字的代码不起作用?

[英]Python: why the code for swapping the largest and the smallest numbers isn't working?

Imagine we have a list of numbers a where all numbers are different, and we want to swap the largest one and the smallest one. 试想一下,我们有编号列表a ,所有的数字都是不同的,我们想换一个最大和最小的一个。 The question is, why this code in Python: 问题是,为什么这段代码在Python中:

a[a.index(min(a))], a[a.index(max(a))] = a[a.index(max(a))], a[a.index(min(a))]

isn't working? 不工作?

Why does it fail? 为什么会失败? Let's take a = [1, 2, 3, 4] as example. 我们以a = [1, 2, 3, 4]为例。

First, the right side is evaluated: 首先,评估右侧:

a[a.index(max(a))], a[a.index(min(a))]    =>    4, 1

That's btw of course the same as 那当然也是如此

max(a), min(a)    =>    4, 1

Next, the assignments happen, from left to right : 接下来,分配从左到右发生:

First, setting a[a.index(min(a))] to 4 makes the list [4, 2, 3, 4] , as the minimum is at the front. 首先,将a[a.index(min(a))]为4使得列表a[a.index(min(a))] [4, 2, 3, 4]作为最小值位于前面。

Then, setting a[a.index(max(a))] to 1 makes the list [1, 2, 3, 4] again, as the maximum has been written at the front, so that's where it is found now and where the 1 gets written. 然后,将a[a.index(max(a))]为1会再次生成列表[1, 2, 3, 4] ,因为最大值已经a[a.index(max(a))] ,所以现在找到它的位置和位置1写的。

Better to get index of max and min first: 最好先获得max和min的索引:

i_min, i_max = a.index(min(a)), a.index(max(a))
a[i_min], a[i_max] = a[i_max], a[i_min] 

Other way result can be unpredictable) 其他方式结果可能无法预测)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM