交换 python 列表中的元素
Swapping elements in lists in python
我有一个列表,我需要将列表中的第一个元素与列表中的最大元素交换。
但为什么代码 1 有效而代码 2 无效:
代码 1:
a = list.index(max(list))
list[0], list[a] = list[a], list[0]
代码 2:
list[0], list[list.index(max(list))] = list[list.index(max(list))], list[0]
我以为 Python 会先计算右侧,然后再将其分配给左侧的名称?
Python将结果存储在多个目标中,从左到右,按该顺序执行赋值目标表达式。
所以你的第二个版本基本上归结为:
temp = list[list.index(max(list))],list[0]
list[0] = temp[0]
list[list.index(max(list))] = temp[1]
请注意 list.index(max(list))
在 list[0]
更改后执行 ,这就是您刚刚存储最大值的地方。
这记录在 Assignment statements documenation:
- 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.
从那时起,每个目标就好像是一个单独的目标,因此下面的文档从左到右适用于每个目标:
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.
如果您更改分配顺序,您的代码将起作用:
list[list.index(max(list))], list[0] = list[0], list[list.index(max(list))]
因为现在 list[list.index(max(list))]
被分配给 first.
我有一个列表,我需要将列表中的第一个元素与列表中的最大元素交换。
但为什么代码 1 有效而代码 2 无效:
代码 1:
a = list.index(max(list))
list[0], list[a] = list[a], list[0]
代码 2:
list[0], list[list.index(max(list))] = list[list.index(max(list))], list[0]
我以为 Python 会先计算右侧,然后再将其分配给左侧的名称?
Python将结果存储在多个目标中,从左到右,按该顺序执行赋值目标表达式。
所以你的第二个版本基本上归结为:
temp = list[list.index(max(list))],list[0]
list[0] = temp[0]
list[list.index(max(list))] = temp[1]
请注意 list.index(max(list))
在 list[0]
更改后执行 ,这就是您刚刚存储最大值的地方。
这记录在 Assignment statements documenation:
- 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.
从那时起,每个目标就好像是一个单独的目标,因此下面的文档从左到右适用于每个目标:
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.
如果您更改分配顺序,您的代码将起作用:
list[list.index(max(list))], list[0] = list[0], list[list.index(max(list))]
因为现在 list[list.index(max(list))]
被分配给 first.