Python 重新排列列表中元素的顺序

Python 重新排列列表中元素的顺序,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我试图重新排列列表中元素的顺序 我想将I+1位置的元素移动到列表的末尾 对于len(列表)-2次 例如,如果我有 >>> 5 6 7 8 9 10 11 12 13 14 15 5 7 8 9 10 11 12 13 14 15 6 5 7 9 10 11 12 13 14 15 6 8 5 7 9 11 12 13 14 15 6 8 10 5 7 9 11 13 14 15 6 8 10 12 5 7 9 11 13 15 6 8 10 12 14 5 7 9

我试图重新排列列表中元素的顺序

我想将I+1位置的元素移动到列表的末尾

对于len(列表)-2次

例如,如果我有

>>> 5 6 7 8 9 10 11 12 13 14 15

5 7 8 9 10 11 12 13 14 15 6

5 7 9 10 11 12 13 14 15 6 8

5 7 9 11 12 13 14 15 6 8 10

5 7 9 11 13 14 15 6 8 10 12

5 7 9 11 13 15 6 8 10 12 14

5 7 9 11 13 15 8 10 12 14 6

5 7 9 11 13 15 8 12 14 6 10

5 7 9 11 13 15 8 12 6 10 14

5 7 9 11 13 15 8 12 6 14 10 # desired output
下面是我的代码,但我无法找到从列表中删除I+1元素并将其附加到列表末尾的方法

代码返回一个错误,表示pop索引超出范围,这非常令人沮丧

def rearrange(sequence):
    test_list = list(sequence)

    length = len(test_list)
    for i in range(length - 2):
        stray_element = test_list.pop(i + 1)
        test_list.append(stray_element)
您发布的代码(经过编辑使其返回,并提供输入序列)对我来说运行良好,并生成所需的输出

my_sequence = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

def rearrange(sequence):
    test_list = list(sequence)

    length = len(test_list)
    for i in range(length - 2):
        stray_element = test_list.pop(i + 1)
        test_list.append(stray_element)
    return test_list

print(rearrange(my_sequence))
产出:

[5, 7, 9, 11, 13, 15, 8, 12, 6, 14, 10]

(作为答案而不是注释发布,主要是因为格式…)

您应该确保序列大于2,因为您从例程的长度中减去2。@Jonah用小序列运行此项,甚至空列表实际上不会导致错误。