可能重复:
Efficient way to shift a list in python
我想将Python列表向右或向左旋转任意数量的项(后者使用负参数)。
如下所示:
>>> l = [1,2,3,4]
>>> l.rotate(0)
[1,2,3,4]
>>> l.rotate(1)
[4,1,2,3]
>>> l.rotate(-1)
[2,3,4,1]
>>> l.rotate(4)
[1,2,3,4]
如何做到这一点呢?
发布于 2012-02-27 06:30:10
def rotate(l, n):
return l[-n:] + l[:-n]
更传统的方向:
def rotate(l, n):
return l[n:] + l[:n]
示例:
example_list = [1, 2, 3, 4, 5]
rotate(example_list, 2)
# [3, 4, 5, 1, 2]
rotate
的参数是一个列表和一个表示移位的整数。该函数使用slicing创建两个新列表,并返回这些列表的串联。rotate
函数不修改输入列表。
发布于 2012-02-27 06:32:35
如果适用,您可以使用collections.deque
作为解决方案:
import collections
d = collections.deque([1,2,3,4,5])
d.rotate(3)
print d
>>> deque([3, 4, 5, 1, 2])
作为奖励,我希望它比内置的list更快。
发布于 2012-02-27 06:36:51
以下函数将向右旋转list l
,x
spaces:
def rotate(l, x):
return l[-x:] + l[:-x]
请注意,只有当x
超出[-len(l), len(l)]
范围时,才会返回原始列表。要使其适用于x
的所有值,请使用:
def rotate(li, x):
return li[-x % len(li):] + li[:-x % len(li)]
https://stackoverflow.com/questions/9457832
复制相似问题