更新时间:2023-11-14 12:06:04
下面显示了借助索引进行此操作的另一种方法。
Another way to do this with the help of indexing is shown below..
def rotate(l, n):
return l[n:] + l[:n]
print(rotate([1, 2, 3, 4, 5], 2))
#output : [3, 4, 5, 1, 2]
仅当n超出 [-len(l),len(l)]
范围时,才返回原始列表。要使其适用于所有n值,请使用:
This will only return the original list if n is outside the range [-len(l), len(l)]
. To make it work for all values of n, use:
def rotate(l, n):
return l[-n % len(l):] + l[:-n % len(l)]