在python列表中交换元素 [英] Swapping elements in lists in python

查看:754
本文介绍了在python列表中交换元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,我需要将列表中的第一个元素与列表中的最大元素交换.

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

但是为什么代码1起作用而代码2却不起作用:

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

代码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会先评估右侧,然后再将其分配给左侧的名称?

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

推荐答案

Python将结果从从左到右存储在多个目标中,并以此顺序执行分配目标表达式.

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]

请注意,list.index(max(list))是在 修改后执行的,这就是您存储最大值的地方.

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

分配声明中对此进行了说明文档化:

This is documented in the 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.

从那里开始,好像每个目标都是一个目标,因此以下文档从左到右适用于每个目标:

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 you changed the order of assignments your code would work:

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

因为现在list[list.index(max(list))]被分配给 first .

这篇关于在python列表中交换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆