0

数字のリストが与えられ、そのうちの 1 つを次の 2 つの数字と交換したい場合。最初の数字を 2 回交換せずに、これを 1 回で行う方法はありますか?

より具体的には、次の swap 関数があるとします。

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 を 2 回呼び出さずに、番号を次の 2 つの番号と交換するにはどうすればよいでしょうか。

例: 次のリストがあります。list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

では、3 を 4 と 5 と一発で入れ替えるにはどうすればよいでしょうか。

期待される出力は

リスト = [0, 1, 2, 4, 5, 3, 6, 7, 8, 9]

4

1 に答える 1

1

このようなもの?

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]
于 2013-11-02T15:51:49.830 に答える