Swapping list with index

2019-09-20 07:16发布

问题:

Just want to ask how do i swap the list at the index with the list that follows it and if the list at the index is on the bottom, swap that with the top. So that the index would swap places with the position the list is with the next number For example Normal = [1,2,3,4] and index of 1 would turn to = [1, 3, 2, 4]. making the 2 and 3 swap places and index of 3 would make [4, 2, 3, 1]

回答1:

def swap(lst, swap_index):
    try:
        next_index = (swap_index + 1) % len(lst)
        lst[swap_index], lst[next_index] = lst[next_index], lst[swap_index]
    except IndexError:
        print "index out of range"
lst = [1,2,3,4]
swap_index = 4
swap(lst,swap_index)
print lst

pay attention that everything in Python is reference, that is to say, the swap function swap elements in place



回答2:

I threw together a quick function which should work with any values, though Hootings way may be better.

def itatchi_swap(x, n):
    x_len = len(x)
    if not 0 <= n < x_len:
        return x
    elif n == x_len - 1:
        return [x[-1]] + x[1:-1] + [x[0]]
    else:
        return x[:n] + [x[n+1]] + [x[n]] + x[n+2:]

And slightly modified to mutate the list:

def itatchi_swap(x, n):
    x_len = len(x)
    if 0 <= n < x_len:
        if n == x_len - 1:
            v = x[0]
            x[0] = x[-1]
            x[-1] = v
        else:
            v = x[n]
            x[n] = x[n+1]
            x[n+1] = v


标签: python list swap