2012-02-26 85 views
62

可能重複:
Efficient way to shift a list in pythonPython列表旋轉

我想用物品任意數量的旋轉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] 

怎麼可能這樣做?

+2

我不使用Python,但如果你有push/pop方法,你可以使用l.push(l.pop())。然後循環它。這將涵蓋前進。 – 2012-02-26 22:29:19

+0

[這個問題](http://stackoverflow.com/questions/2150108/efficient-way-to-shift-a-list-in-python)有幫助嗎? – simchona 2012-02-26 22:30:18

+0

這個問題似乎相關:http://stackoverflow.com/questions/1212025/moving-values-in-a-list-in-python – 2012-02-26 22:30:36

回答

118
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函數不會修改輸入列表。

+0

不錯,簡單。它旋轉的方向與問題中指定的方向相反。 – 2012-02-26 22:36:40

+0

愛的優雅! – varunl 2012-02-26 22:41:05

+0

@DrewNoakes它確實是這樣... – YXD 2012-02-26 22:47:31

82

如果適用,您可以使用collections.deque作爲一種解決方案:

import collections 

d = collections.deque([1,2,3,4,5]) 
d.rotate(3) 

print d 
>>> deque([3, 4, 5, 1, 2]) 

作爲獎勵,我希望它會比內置列表更快。

+3

對於未來的讀者:'collections.deque rotate()'比根據https://wiki.python.org/moin/TimeComplexity – Geoff 2016-12-16 17:35:04

+0

更快切片不應該提及集合默認情況下向左旋轉? – 2017-07-24 03:17:24

+0

@HasanIqbalAnik deque.rotate向右旋轉https://docs.python.org/3/library/collections.html#collections.deque.rotate – miles82 2017-12-10 20:05:27

14

下面的函數將旋轉列表lx空間向右:

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

有沒有辦法這一點沒有'return'?我試過'l = l [n:] + l [:n]'但是當我嘗試返回'l'時,我得到原文。 – GinKin 2014-03-18 17:46:51

+0

@GinKin爲什麼沒有回報?這就是你從一個函數返回的東西。我的意思是,你可以使用lambda,但這只是讓隱含的返回。 – 2014-03-18 17:54:42

+0

我想「到位」,使其因此它不會返回任何東西,如果我輸入'運行功能之後>>> l'我會得到一個旋轉的列表,而不是原來的。 – GinKin 2014-03-18 17:59:19

4
>>> 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]