Python 值交换什么都不做

标签 python list swap

我目前正在编写一个列表排序函数,我试图将列表的最小值与列表的第一个元素交换:

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/

相关文章:

python - 使用cursor.fetchall()返回空数据框

python - 将 PyCharm 中的项目解释器设置为 Python 3.7 会导致有关 Python 3.5 的虚假代码不兼容消息

c - 如何在结构中交换数组的结构元素 - C

python - 交换数组中的元素

C 链表中的冒泡排序

Python Selenium 单击带有类的按钮

python - 从 GPS 点绘制线

python - 列表成员测试或集合

python - 字符串文字中的反斜杠是什么意思?

scala - 左连接两个列表