交换索引列表 [英] Swapping list with index

查看:95
本文介绍了交换索引列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只想问一下如何将索引处的列表与它后面的列表交换,并且如果索引处的列表在底部,则将其与顶部交换. 这样索引将与列表与下一个数字的位置交换位置.例如,Normal = [1,2,3,4],而索引1将变为= [1、3、2、4].设置2和3的交换位置,索引3将使[4,2,3,1]

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]

推荐答案

尽管Hootings方式可能更好,但我组合了一个快速函数,该函数应适用于任何值.

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

这篇关于交换索引列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆