Swapping list with index

六月ゝ 毕业季﹏ 提交于 2019-12-14 03:34:39

问题


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


来源:https://stackoverflow.com/questions/33707997/swapping-list-with-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!