![](/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.