![](/img/trans.png)
[英]Combine n elements in first half of list with elements in other half of a list, if number of elements in a list is greater than 2
[英]Rotating a list n times when n is greater than the number of elements in list
只要旋转次数不超过列表中的元素数,以下 function(取自此 SO 问题)就可以正常工作。 之后它只是重复原来的列表。 是否可以进行任何修改以将列表旋转任意次数?
def shift(l,n):
return l[n:] + l[:n]
将modulo应用于参数:
def shift(l,n):
if not len(l): # to avoid error on modulo operator
return []
n = n % len(l)
return l[n:] + l[:n]
假设列表中有五个元素,旋转次数为八,那么基本上只需要旋转列表 3 次。 因为在第五次轮换时,您的列表与原始列表相同,因此您需要轮换三次。
def left_shift(lst, n):
n= n % len(lst)
return lst[n:]+lst[:n]
def right_shift(lst, n):
n= n % len(lst)
return lst[-n:] + lst[:-n]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.