在python中旋转列表最有效的方法是什么? 现在我有这样的东西:

>>> def rotate(l, n):
...     return l[n:] + l[:n]
... 
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]

有没有更好的办法?


当前回答

下面是一个高效的算法,不需要使用任何额外的数据结构:

旋转(nums: List[int], k: int):

    k = k%len(nums)
    l, r = 0, len(nums)-1
    while (l<r):
        nums[l], nums[r]= nums[r], nums[l]
        l,r=l+1,r-1
    
    l,r = 0, k-1
    while (l<r):
        nums[l], nums[r]=nums[r], nums[l]
        l,r=l+1,r-1
        
    l,r=k,len(nums)-1
    while (l<r):
        nums[l], nums[r]=nums[r], nums[l]
        l,r=l+1,r-1

其他回答

如果只使用pop(0)呢?

list.pop([我]) 删除列表中给定位置的项,并返回它。如果 如果没有指定索引,a.pop()将删除并返回中的最后一项 列表中。(方法签名中i周围的方括号 表示参数是可选的,而不是您应该键入square 括号在那个位置。你会经常在 Python库参考。)

我以这个成本模型作为参考:

http://scripts.mit.edu/~6.006/fall07/wiki/index.php?title=Python_Cost_Model

切片列表和连接两个子列表的方法是线性时间操作。我建议使用pop,这是一个常数时间操作,例如:

def shift(list, n):
    for i in range(n)
        temp = list.pop()
        list.insert(0, temp)

我也对此感兴趣,并将一些建议的解决方案与perfplot(我的一个小项目)进行了比较。

事实证明凯利·邦迪的建议

tmp = data[shift:]
tmp += data[:shift]

在所有轮班中都表现良好。

从本质上讲,perfplot执行增加大型数组的移位并测量时间。以下是调查结果:

Shift = 1:

Shift = 100:


代码重现情节:

import numpy
import perfplot
import collections


shift = 100


def list_append(data):
    return data[shift:] + data[:shift]


def list_append2(data):
    tmp = data[shift:]
    tmp += data[:shift]
    return tmp


def shift_concatenate(data):
    return numpy.concatenate([data[shift:], data[:shift]])


def roll(data):
    return numpy.roll(data, -shift)


def collections_deque(data):
    items = collections.deque(data)
    items.rotate(-shift)
    return items


def pop_append(data):
    data = data.copy()
    for _ in range(shift):
        data.append(data.pop(0))
    return data


b = perfplot.bench(
    setup=lambda n: numpy.random.rand(n).tolist(),
    kernels=[
        list_append,
        list_append2,
        roll,
        shift_concatenate,
        collections_deque,
        pop_append,
    ],
    n_range=[2 ** k for k in range(7, 20)],
    xlabel="len(data)",
)
b.show()
b.save("shift100.png")

对于一个列表X = ['a', 'b', 'c', 'd', 'e', 'f'],并且shift值小于列表长度,我们可以如下所示定义函数list_shift()

def list_shift(my_list, shift):
    assert shift < len(my_list)
    return my_list[shift:] + my_list[:shift]

的例子,

list_shift (X, 1)返回(' b ', ' c ', ' d ', ' e ', ' f ', ' '] list_shift (X, 3)返回(' d ', ' e ', ' f ', ' ', ' b ', ' c ']

我认为你有最有效的方法

def shift(l,n):
    n = n % len(l)  
    return l[-U:] + l[:-U]