Python 从某个元素开始重新排列列表
Python rearrange list starting from a certain element
我有一个 python 列表和一个项目的索引 我想在列表上从索引后的元素开始循环。
例如我有:
original_list = [1,2,3,4,5]
my_index = 2
new_list = [4,5,1,2,3]
我正在努力实现新列表。
只需使用列表slicing,像这样
>>> original_list, my_index = [1, 2, 3, 4, 5], 2
>>> original_list[my_index + 1:] + original_list[:my_index + 1]
[4, 5, 1, 2, 3]
或者您可以使用 collections.deque 并且可以使用 deque.rotate
.
In [70]: original_list = [1,2,3,4,5]
In [71]: import collections
In [72]: deq = collections.deque(original_list)
In [77]: deq.rotate(2)
In [78]: deq
Out[78]: deque([4, 5, 1, 2, 3])
这是另一种可能性:
>>> olist = [1,2,3,4,5]
>>> print [olist[n-2] for n in xrange(len(olist))]
[4, 5, 1, 2, 3]
我有一个 python 列表和一个项目的索引 我想在列表上从索引后的元素开始循环。 例如我有:
original_list = [1,2,3,4,5]
my_index = 2
new_list = [4,5,1,2,3]
我正在努力实现新列表。
只需使用列表slicing,像这样
>>> original_list, my_index = [1, 2, 3, 4, 5], 2
>>> original_list[my_index + 1:] + original_list[:my_index + 1]
[4, 5, 1, 2, 3]
或者您可以使用 collections.deque 并且可以使用 deque.rotate
.
In [70]: original_list = [1,2,3,4,5]
In [71]: import collections
In [72]: deq = collections.deque(original_list)
In [77]: deq.rotate(2)
In [78]: deq
Out[78]: deque([4, 5, 1, 2, 3])
这是另一种可能性:
>>> olist = [1,2,3,4,5]
>>> print [olist[n-2] for n in xrange(len(olist))]
[4, 5, 1, 2, 3]