Python在列表中移动数字

时间:2013-10-29 19:51:35

标签: python-3.x

如何在给定列表中移动数字?

例如(如果我移动5):

example_list = [5,6,7,10,11,12]

输出:

[6,7,5,10,11,12]

或如果我移动12输出:

[5,12,6,7,10,11]

是否有内置的Python函数可以让我这样做?

3 个答案:

答案 0 :(得分:4)

您可以使用列表的内置popinsert功能。在这里,您可以指定要弹出的元素的索引以及要将其插入的索引。

example_list = [5,6,7,10,11,12]
example_list.insert(2,example_list.pop(0))
  

[6,7,5,10,11,12]

和第二个例子:

example_list.insert(0,example_list.pop(5))
  

[12,6,7,5,10,11]

这也可以分两步完成。

element = example_list.pop(5)
example_list.insert(0,element)

顺便说一句,如果您不想自己指定索引,可以使用index函数查找值的第一个索引

element = example_list.pop(example_list.index(12))
example_list.insert(0,element)

答案 1 :(得分:2)

使用collections.deque.rotate

>>> from collections import deque
>>> lis = [5,6,7,10,11,12]
>>> d = deque(lis)
>>> d.rotate(1)
>>> d
deque([12, 5, 6, 7, 10, 11])
>>> d.rotate(-2)
>>> d
deque([6, 7, 10, 11, 12, 5])

deque.rotate的帮助:

rotate(...)
    Rotate the deque n steps to the right (default n=1).  If n is negative,
    rotates left.

在7之后移动5:

>>> lis = [5,6,7,10,11,12]
>>> x = lis.pop(lis.index(5))
>>> lis.insert(lis.index(7)+1 , x)
>>> lis
[6, 7, 5, 10, 11, 12]

请注意list.index返回第一个匹配项的索引,以获取所有匹配项的索引使用enumerate

答案 2 :(得分:1)

你可以这样做:

def move(a_list, original_index, final_index):
    a_list.insert(final_index, a_list.pop(original_index))
    return a_list

示例:

>>> move([5,6,7,10,11,12], 0, 2)
[6,7,5,10,11,12]

如果你想移动列表中的前5个,那么你可以这样做:

>>> my_list = [5,6,7,10,11,12]
>>> move(my_list, my_list.index(5), 2)
[6,7,5,10,11,12]