如果给我一个数字列表,我想把其中的一个与下两个数字交换。 有没有一种方法可以一次性完成,而不需要将第一个数字交换两次?在
更具体地说,假设我有以下交换函数:
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]
像这样?在
相关问题 更多 >
编程相关推荐