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

2024-06-06 10:10:15 发布

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

一篇课文用七个字母分组。每个组都用键6015423(在索引6上有索引0的字母,在索引0上有索引1的字母,在索引1...上有索引2的字母)进行置乱。你知道吗

我的代码没有使用正确的单词“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后面插入两个空行,否则,我的代码没有空行。)


Tags: 代码forindex错误字母单词list省略
2条回答

因为列表.索引('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

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

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)

相关问题 更多 >