python中交换两个列表元素的位置,在python列表中交换元素

本文解析了两种Python代码在尝试交换列表中第一个元素和最大值位置的差异,揭示了Python中多重赋值的执行顺序问题。第一种代码按预期工作,而第二种由于表达式评估顺序导致错误。理解目标列表作为多重赋值目标的执行规则至关重要。
摘要由CSDN通过智能技术生成

I have a list and I need to swap the 1st element in the list with the maximum element in the list.

But why does code 1 work while code 2 doesn't:

code 1:

a = list.index(max(list))

list[0], list[a] = list[a], list[0]

code 2:

list[0], list[list.index(max(list))] = list[list.index(max(list))], list[0]

I thought Python would first evaluate the right-hand side before assigning it to the names on the left?

解决方案

Python stores results in multiple targets from left to right, executing the assignment target expression in that order.

So your second version essentially comes down to this:

temp = list[list.index(max(list))],list[0]

list[0] = temp[0]

list[list.index(max(list))] = temp[1]

Note that the list.index(max(list)) is executed after list[0] was altered, and that's where you just stored the maximum value.

If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

From there on out it is as if each target is a single target, so the documentation that follows applies from left to right to each target:

Assignment of an object to a single target is recursively defined as follows.

[...]

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If you changed the order of assignments your code would work:

list[list.index(max(list))], list[0] = list[0], list[list.index(max(list))]

because now list[list.index(max(list))] is assigned to first.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值