交换列表中的第一项和最后一项 [英] Swapping first and last items in a list

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

问题描述

如何交换给定列表中的数字?

How can I go about swapping numbers in a given list?

例如:

list = [5,6,7,10,11,12]

我想将125交换.

是否有内置的Python函数可以让我做到这一点?

Is there an built-in Python function that can allow me to do that?

推荐答案

>>> lis = [5,6,7,10,11,12]
>>> lis[0], lis[-1] = lis[-1], lis[0]
>>> lis
[12, 6, 7, 10, 11, 5]

上述表达式的评估顺序:

expr3, expr4 = expr1, expr2

RHS上的第一项收集在一个元组中,然后元组被拆包并分配给LHS上的项目.

First items on RHS are collected in a tuple, and then that tuple is unpacked and assigned to the items on the LHS.

>>> lis = [5,6,7,10,11,12]
>>> tup = lis[-1], lis[0]
>>> tup
(12, 5)
>>> lis[0], lis[-1] = tup
>>> lis
[12, 6, 7, 10, 11, 5]

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

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