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

时间:2018-02-23 12:36:01

标签: python python-3.x list

只要旋转次数不超过列表中的元素数,以下函数(取自this SO question)就可以正常工作。之后,它只重复原始列表。是否有任何修改可以进行多次轮换列表?

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

sample output

1 个答案:

答案 0 :(得分:3)

将模数应用于参数:

def shift(l,n):
  if not len(l): # to avoid error on modulo operator
    return [] 
  n = n % len(l)
  return l[n:] + l[:n]
相关问题