如何在python列表中交换项目的位置?

如何在python列表中交换项目的位置?,python,list,reindex,Python,List,Reindex,正文由七个字母组成。每组用6015423键进行置乱,索引6上有索引0的字母,索引0上有索引1的字母,索引1上有索引2的字母 与正确的单词serpent不同,serpent只在前七个字母组中使用,当%7被忽略时,同样的问题也会发生。我的代码生成一个从索引4开始的错误结果:serpsne 错在哪里 list=['e','r','n','t','e','p','s'] clear=[] for x in list: if list.index(x)%7==0: a=li

正文由七个字母组成。每组用6015423键进行置乱,索引6上有索引0的字母,索引0上有索引1的字母,索引1上有索引2的字母

与正确的单词serpent不同,serpent只在前七个字母组中使用,当%7被忽略时,同样的问题也会发生。我的代码生成一个从索引4开始的错误结果:serpsne

错在哪里

list=['e','r','n','t','e','p','s']
clear=[]
for x in list:    
    if list.index(x)%7==0:
        a=list[list.index(x)+6]
    elif list.index(x)%7==1:
        a=list[list.index(x)-1]
    elif list.index(x)%7==2:
        a=list[list.index(x)-1]
    elif list.index(x)%7==3:
        a=list[list.index(x)+2]
    elif list.index(x)%7==4:
        a=x
    elif list.index(x)%7==5:
        a=list[list.index(x)-3]
    else:               
        a=list[list.index(x)-6]
    clear.append(a)
clear=''.join(clear)
print(clear)

不知道为什么这个框在for之后插入两个空行,否则,我的代码没有空行。

不知道为什么要这么做!试试下面这个:

lst=['e','r','n','t','e','p','s']
clear=[]
key='6015423'
for x in key:
    clear.append(lst[int(x)])

clear=''.join(clear)
print(clear)

因为list.index“e”总是0

它将查找第一次出现的“e”的索引,而不是第二次出现的索引,因此它将永远不会执行此操作:

elif list.index(x)%7==4:
    a=x
尝试运行以下代码:

list=['e','r','n','t','e','p','s']
for x in list:
print ( list.index(x))

您将得到0123056而不是0123456

您可以通过索引交换值。列表[0],列表[1]=列表[1],列表[0]非常感谢。我之所以使用模的东西,是因为“list”不同于我上面给出的示例,它由许多七个字母组成,所有字母都用相同的键进行转置。我将尝试在代码中增加“key”,使其与“list”一样长。我会记住这一点,谢谢!有没有办法找到一个项目进一步出现的索引?当然,您可以这样做,例如,如果lst[i]='e'],那么可以将所有出现的事件都称为[i for i in rangelenlst]顺便说一句,将列表变量称为'list'可能不是一个好主意,因为'list'也是类的名称