在python中用列表中的两个数字交换一个数字

2024-04-25 01:11:30 发布

您现在位置:Python中文网/ 问答频道 /正文

如果给我一个数字列表,我想把其中的一个与下两个数字交换。 有没有一种方法可以一次性完成,而不需要将第一个数字交换两次?在

更具体地说,假设我有以下交换函数:

def swap_number(list, index):
    '''Swap a number at the given index with the number that follows it.
Precondition: the position of the number being asked to swap cannot be the last
or the second last'''

    if index != ((len(list) - 2) and (len(list) - 1)):
        temp = list[index]
        list[index] = list[index+1]
        list[index+1] = temp

现在,我如何使用这个函数将一个数与下两个数交换,而不必对这个数调用两次swap。在

例如:我有以下列表:list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

现在,我如何在一次射击中用3和4和5交换?在

预期产出将是

列表=[0,1,2,4,5,3,6,7,8,9]


Tags: the方法函数number列表indexlendef
1条回答
网友
1楼 · 发布于 2024-04-25 01:11:30

像这样?在

def swap(lis, ind):
    lis.insert(ind+2, lis.pop(ind)) #in-place operation, returns `None`
    return lis
>>> lis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lis = swap(lis, 3)
>>> lis
[0, 1, 2, 4, 5, 3, 6, 7, 8, 9]

相关问题 更多 >