在python中转移列表的最有效方法是什么?现在我有这样的事情:>>> def shift(l, n):... return l[n:] + l[:n]... >>> l = [1,2,3,4]>>> shift(l,1)[2, 3, 4, 1]>>> shift(l,2)[3, 4, 1, 2]>>> shift(l,0)[1, 2, 3, 4]>>> shift(l,-1)[4, 1, 2, 3]有更好的办法吗?在python中转换列表的有效方法
3 回答

慕村225694
TA贡献1880条经验 获得超4个赞
A collections.deque
rotate()
from collections import deque items = deque([1, 2])items.append(3) # deque == [1, 2, 3]items.rotate(1) # The deque is now: [3, 1, 2]items.rotate(-1) # Returns deque to original state: [1, 2, 3]item = items.popleft() # deque == [2, 3]

呼啦一阵风
TA贡献1802条经验 获得超6个赞
roll
>>> import numpy>>> a=numpy.arange(1,10) #Generate some data>>> numpy.roll(a,1)array([9, 1, 2, 3, 4, 5, 6, 7, 8]) >>> numpy.roll(a,-1)array([2, 3, 4, 5, 6, 7, 8, 9, 1])>>> numpy.roll(a,5)array([5, 6, 7, 8, 9, 1, 2, 3, 4]) >>> numpy.roll(a,9)array([1, 2, 3, 4, 5, 6, 7, 8, 9])
添加回答
举报
0/150
提交
取消