在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]
有更好的方法吗?
我想你正在寻找这个:
a.insert(0, x)
def move(arr, n):
return [arr[(idx-n) % len(arr)] for idx,_ in enumerate(arr)]
def solution(A, K):
if len(A) == 0:
return A
K = K % len(A)
return A[-K:] + A[:-K]
# use case
A = [1, 2, 3, 4, 5, 6]
K = 3
print(solution(A, K))
A = [3, 8, 9, 7, 6]
K = 3
[9, 7, 6, 3, 8]
。进行了三次旋转:[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
举个例子,假设
A = [0, 0, 0]
K = 1
这个函数应该返回[0, 0, 0]
给定
A = [1, 2, 3, 4]
K = 4
[1, 2, 3, 4]
。def rotate(arr, shift):
pivot = shift % len(arr)
dst = 0
src = pivot
while (dst != src):
arr[dst], arr[src] = arr[src], arr[dst]
dst += 1
src += 1
if src == len(arr):
src = pivot
elif dst == pivot:
pivot = src
我有类似的东西。例如,将其向右移动两个位置...
def Shift(*args):
return args[len(args)-2:]+args[:len(args)-2]
我认为你已经找到了最有效的方法。
def shift(l,n):
n = n % len(l)
return l[-U:] + l[:-U]
Jon Bentley在编程珠玑(第2篇)中描述了一种优雅且高效的算法,用于将n
个元素的向量x
左移i
个位置:
这可以翻译成Python如下:Let's view the problem as transforming the array
ab
into the arrayba
, but let's also assume that we have a function that reverses the elements in a specified portion of the array. Starting withab
, we reversea
to getarb
, reverseb
to getarbr
, and then reverse the whole thing to get(arbr)r
, which is exactlyba
. This results in the following code for rotation:reverse(0, i-1) reverse(i, n-1) reverse(0, n-1)
def rotate(x, i):
i %= len(x)
x[:i] = reversed(x[:i])
x[i:] = reversed(x[i:])
x[:] = reversed(x)
return x
演示:
>>> def rotate(x, i):
... i %= len(x)
... x[:i] = reversed(x[:i])
... x[i:] = reversed(x[i:])
... x[:] = reversed(x)
... return x
...
>>> rotate(list('abcdefgh'), 1)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']
>>> rotate(list('abcdefgh'), 3)
['d', 'e', 'f', 'g', 'h', 'a', 'b', 'c']
>>> rotate(list('abcdefgh'), 8)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> rotate(list('abcdefgh'), 9)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']
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)
collections.deque
。 - herrfz
numpy.roll
函数用于将数组沿指定轴滚动。该函数接受两个参数:a
是需要滚动的数组,shift
是滚动的偏移量。import numpy as np a = np.array([1, 2, 3, 4, 5]) print(np.roll(a, 2)) # [4 5 1 2 3]
在上面的示例中,原始数组[1, 2, 3, 4, 5]
沿着其第一个轴滚动了 2 个位置。因此,最后两个元素4
和5
移动到了数组开头,而前三个元素1
、2
和3
则被推到了数组的末尾。 - BoltzmannBrain