简体   繁体   English

当 n 大于列表中元素的数量时,旋转列表 n 次

[英]Rotating a list n times when n is greater than the number of elements in list

The following function (taken from this SO question ) works fine as long as number of rotations does not exceed the number of elements in list.只要旋转次数不超过列表中的元素数,以下 function(取自此 SO 问题)就可以正常工作。 After that it just repeats the original list.之后它只是重复原来的列表。 Is there any modification that can be done to rotate a list any number of times?是否可以进行任何修改以将列表旋转任意次数?

def shift(l,n):
  return l[n:] + l[:n]

示例输出

Apply modulo to the argument: 将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]

Suppose you have five elements in the list, and the rotation number is eight, then you basically need to rotate your list just for three times.假设列表中有五个元素,旋转次数为八,那么基本上只需要旋转列表 3 次。 Because at the fifth rotation, your list is same as original list, so remaining three times you need to rotate.因为在第五次轮换时,您的列表与原始列表相同,因此您需要轮换三次。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM