我有一个Python列表和一个索引,我想从该索引后的元素开始循环遍历列表。例如,我有:
original_list = [1,2,3,4,5]
my_index = 2
new_list = [4,5,1,2,3]
我正在尝试实现新列表。
只需使用列表切片,如下所示:
>>> 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]
itertools.chain
,但这只对非常大的列表有帮助。 - jamylaklist(islice(cycle(original_list), my_index+1, my_index+len(original_list)+1)
,但我想不出有什么用处哈哈。 - jamylak