我正在尝试重新排列列表中元素的顺序。
我想把I+1位置的元素移到列表的末尾,
对连(名单)-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)发布于 2018-11-12 14:21:03
您发布的代码(在编辑它以使其返回并提供输入序列之后)对我很好,并产生了所需的输出。
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](张贴为回复而非评论,主要是因为格式.)
https://stackoverflow.com/questions/53263971
复制相似问题