Python重新排列列表,从特定元素开始

5

我有一个Python列表和一个索引,我想从该索引后的元素开始循环遍历列表。例如,我有:

original_list = [1,2,3,4,5]
my_index = 2
new_list = [4,5,1,2,3]

我正在尝试实现新列表。

3个回答

7

只需使用列表切片,如下所示:

>>> 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]

对于大型列表,请使用itertools.islice。 - fredtantini
@fredtantini 和 itertools.chain,但这只对非常大的列表有帮助。 - jamylak
另一种选择是 list(islice(cycle(original_list), my_index+1, my_index+len(original_list)+1),但我想不出有什么用处哈哈。 - jamylak

4

你可以使用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])

0

这是另一种可能性:

>>> olist = [1,2,3,4,5]
>>> print [olist[n-2] for n in xrange(len(olist))]
[4, 5, 1, 2, 3]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接