用索引交换列表

2024-04-26 21:39:28 发布

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

我只想问一下如何将索引处的列表与其后的列表交换,如果索引处的列表在底部,则将其与顶部交换。 因此索引将与列表与下一个数字的位置交换位置,例如Normal=[1,2,3,4],而index of 1将变为=[1,3,2,4]。将2和3个交换位置和索引设为3将使[4,2,3,1]


Tags: of列表index数字normal
2条回答
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

请注意,Python中的所有内容都是引用,也就是说,swap函数交换元素

我创建了一个可以处理任何值的快速函数,不过Hootings方法可能更好。你知道吗

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:]

稍加修改以改变列表:

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

相关问题 更多 >