我想用物品任意數量的旋轉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]
怎麼可能這樣做?
我想用物品任意數量的旋轉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]
怎麼可能這樣做?
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
函數不會修改輸入列表。
如果適用,您可以使用collections.deque
作爲一種解決方案:
import collections
d = collections.deque([1,2,3,4,5])
d.rotate(3)
print d
>>> deque([3, 4, 5, 1, 2])
作爲獎勵,我希望它會比內置列表更快。
對於未來的讀者:'collections.deque rotate()'比根據https://wiki.python.org/moin/TimeComplexity – Geoff 2016-12-16 17:35:04
更快切片不應該提及集合默認情況下向左旋轉? – 2017-07-24 03:17:24
@HasanIqbalAnik deque.rotate向右旋轉https://docs.python.org/3/library/collections.html#collections.deque.rotate – miles82 2017-12-10 20:05:27
下面的函數將旋轉列表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)]
>>> l=[1,2,3,4]
>>> l[1:]+l[:1]
[2, 3, 4, 1]
>>> l=[1,2,3,4]
>>> l[2:]+l[:2]
[3, 4, 1, 2]
>>> l[-1:]+l[:-1]
[4, 1, 2, 3]
一般旋轉n
向左或向右移動(負y)(在調用rotate
正y),則:
def rotate(l, y=1):
if len(l) == 0:
return l
y = y % len(l) # Why? this works for negative y
return l[y:] + l[:y]
如果你想旋轉的方向與你的例子相同,只是否定y
旋轉。
def rotate(l, y=1):
if len(l) == 0:
return l
y = -y % len(l) # flip rotation direction
return l[y:] + l[:y]
我不使用Python,但如果你有push/pop方法,你可以使用l.push(l.pop())。然後循環它。這將涵蓋前進。 – 2012-02-26 22:29:19
[這個問題](http://stackoverflow.com/questions/2150108/efficient-way-to-shift-a-list-in-python)有幫助嗎? – simchona 2012-02-26 22:30:18
這個問題似乎相關:http://stackoverflow.com/questions/1212025/moving-values-in-a-list-in-python – 2012-02-26 22:30:36