我目前正在编写一个列表排序函数,我试图将列表的最小值与列表的第一个元素交换:
foo = [4, 7, 2, 9]
foo[0], foo[foo.index(min(foo))] = foo[foo.index(min(foo))], foo[0]
我期待的结果:
foo = [2, 7, 4, 9]
但是我得到了
foo = [4, 7, 2, 9]
一切都没有改变。有帮助吗?
最佳答案
让我们用一些临时变量来分解它,看看发生了什么:
>>> foo = [4, 7, 2, 9]
>>> tup = foo[foo.index(min(foo))], foo[0]
>>> print tup
(2, 4)
>>> foo[0] = tup[0]
>>> print foo
[2, 7, 2, 9]
>>> dx = foo.index(min(foo))
>>> print dx
0
>>> foo[dx] = tup[1] # foo[dx] equivalent to foo[foo.index(min(foo))]
>>> print foo
[4, 7, 2, 9]
赋值的效果是将 2
赋值给 foo[0]
。然后将 4
分配给 foo
最小值的索引,该值被计算为 foo[0]
因为你刚刚分配给它。
这是另一种通过记下计算顺序来查看它的方法:
foo[0], foo[foo.index(min(foo))] = foo[foo.index(min(foo))], foo[0]
1_______
2__________________
3_______________________ 4_____
5_______________________________
6_____
7_______
8__________________
9_______________________
1 find min
2 find index
3 get item by index
4 get item by index
5 make tuple
6 assign to foo at index 0 from left hand side of tuple from step 5)
7 find min
8 find index
9 assign to foo at index from step 8 from right hand side of tuple from step 5
关于Python 值交换什么都不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20106963/