Python 交换列表中的第一项和最后一项

Python 交换列表中的第一项和最后一项,python,list,python-2.7,python-3.x,swap,Python,List,Python 2.7,Python 3.x,Swap,如何在给定列表中交换数字 例如: list = [5,6,7,10,11,12] 我想用5交换12 是否有一个内置的Python函数允许我这样做 >>> 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上的第一个项目收集在一个

如何在给定列表中交换数字

例如:

list = [5,6,7,10,11,12]
我想用
5
交换
12

是否有一个内置的Python函数允许我这样做

>>> 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上的项目

>>> 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]

使用要更改的号码的索引

In [38]: t = [5,6,7,10,11,12]

In [40]: index5 = t.index(5) # grab the index of the first element that equals 5

In [41]: index12 = t.index(12) # grab the index of the first element that equals 12

In [42]: t[index5], t[index12] = 12, 5 # swap the values

In [44]: t
Out[44]: [12, 6, 7, 10, 11, 5]
然后你可以做一个快速交换功能

def swapNumbersInList( listOfNums, numA, numB ):
    indexA = listOfNums.index(numA)
    indexB = listOfNums.index(numB)

    listOfNums[indexA], listOfNums[indexB] = numB, numA

# calling the function
swapNumbersInList([5,6,7,10,11,12], 5, 12)
另一种方式(不那么可爱):


您可以使用此代码进行交换

list[0],list[-1] = list[-1],list[0]
希望这有帮助:)

您可以使用“*”运算符

my_list = [1,2,3,4,5,6,7,8,9]
a, *middle, b = my_list
my_new_list = [b, *middle, a]
my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
my_new_list
[9, 2, 3, 4, 5, 6, 7, 8, 1]
阅读了解更多信息。

这就是我最终的工作方式。
你好谢谢你的及时回复!你能解释一下这段代码中发生了什么吗。。。我对编程相当陌生。@user2891763我添加了一些解释。这种交换技术也适用于
numpy.ndarray
什么指定了要交换的元素?值(每12个替换为5,每5个替换为12)、位置(在第一位和最后一位切换值)或其他规则?例如,对于
[5,5,12,12]
,您希望发生什么?我希望列表中的最后一个数字始终与列表中的第一个数字交换。。。。在任何给定的列表中。是的。同样适用于
numpy.ndarray
array = [5,2,3,6,1,12]
temp = ''
lastvalue = 5

temp = array[0]
array[0] = array[lastvalue]
array[lastvalue] = temp

print(array)
my_list = [1,2,3,4,5,6,7,8,9]
a, *middle, b = my_list
my_new_list = [b, *middle, a]
my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
my_new_list
[9, 2, 3, 4, 5, 6, 7, 8, 1]
def swap(the_list):
    temp = the_list[0]
    the_list[0] = the_list[-1]
    the_list[-1] = temp
    return the_list