在列表中交换第一个和最后一个项目

6

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

例如:

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

我想用 5 替换 12
是否有Python内置函数能够实现这个功能?

1
你想要交换哪些元素?是值(将每个12替换为5,每个5替换为12),位置(交换第一个和最后一个位置的值)还是其他规则?例如,对于[5,5,12,12],你想要发生什么? - DSM
1
我希望在任何给定的列表中,将列表中的最后一个数字始终与第一个数字交换。 - user2891763
7个回答

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

首先,右侧的项目将被收集到一个元组中,然后将该元组拆包并分配给左侧的项。

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

你好!感谢您的及时回复!您能否解释一下这段代码中发生了什么......我在编程方面还比较新手。 - user2891763
1
@user2891763 我已经添加了一些解释。 - Ashwini Chaudhary
这种交换技术同样适用于numpy.ndarray - daparic

3
您可以使用“*”运算符。
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]

点击此处获取更多信息。


3
您可以使用以下代码进行交换:
list[0],list[-1] = list[-1],list[0]

是的。对于 numpy.ndarray 也适用。 - daparic

0
array = [5,2,3,6,1,12]
temp = ''
lastvalue = 5

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

print(array)

希望这能帮到你 :)

0

这是最终对我起作用的代码。

def swap(the_list):
    temp = the_list[0]
    the_list[0] = the_list[-1]
    the_list[-1] = temp
    return the_list

0
使用要更改的数字的索引。
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)

0

另一种方式(不太可爱):

mylist   = [5, 6, 7, 10, 11, 12]
first_el = mylist.pop(0)   # first_el = 5, mylist = [6, 7, 10, 11, 12]
last_el  = mylist.pop(-1)  # last_el = 12, mylist = [6, 7, 10, 11]
mylist.insert(0, last_el)  # mylist = [12, 6, 7, 10, 11]
mylist.append(first_el)    # mylist = [12, 6, 7, 10, 11, 5]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接