Ami*_*zan 5 python list python-2.7
我想做一个脚本。程序应该得到一些L包含值和自然数的列表N。
如果N>0,则列表的对象N向左移动步骤。
如果N<0,则列表的对象abs(N)向右移动。
如果N=0列表保持不变...
例如: 对于N=1和L=[1,2,3,4,5],输出为[2,3,4,5,1]。
对于相同的列表,N=-1输出是[5,1,2,3,4]
我实际上是使用collection.deque来做到的,但我只想用列表、for 循环和“if”来做到这一点。
我无法理解如何使对象移动。
l = input("enter list:")
N = input("enter number of rotations:")
import collections
d = collections.deque(l)
d.rotate(-N)
print d
Run Code Online (Sandbox Code Playgroud)
您可以使用列表切片:
def rotate(L, N):
if not L or N % len(L) == 0:
return L
return L[N % len(L):] + L[:N % len(L)]
L = [1, 2, 3, 4, 5]
for N in range(-3, 4):
print(rotate(L, N))
Run Code Online (Sandbox Code Playgroud)
输出:
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用 a list,则旋转的时间复杂度通常与列表中的元素数量成线性关系,因为您必须移动所有现有元素。deque.rotate()另一方面, 是O(k),k是步数。因此,如果您需要多次旋转deque.rotate()是正确的选择。