我想将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]怎么可能这样做?
3 回答

SMILET
TA贡献1796条经验 获得超4个赞
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是一个列表和一个表示移位的整数。该函数使用切片创建两个新列表,并返回这些列表的连接。该rotate功能不会修改输入列表。

GCT1015
TA贡献1827条经验 获得超4个赞
如果适用,您可以将其collections.deque用作解决方案:
import collections
d = collections.deque([1,2,3,4,5])
d.rotate(3)
print d
>>> deque([3, 4, 5, 1, 2])
作为奖励,我希望它比内置列表更快。

Smart猫小萌
TA贡献1911条经验 获得超7个赞
以下函数将旋转列表l,x右侧空格:
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)]
添加回答
举报
0/150
提交
取消