def rotate(l, n):
return l[-n:] + l[:-n]
More conventional direction:
def rotate(l, n):
return l[n:] + l[:n]
Example:
example_list = [1, 2, 3, 4, 5]
rotate(example_list, 2)
# [3, 4, 5, 1, 2]
The arguments to rotate
are a list and an integer denoting the shift. The function creates two new lists using slicing and returns the concatenatenation of these lists. The rotate
function does not modify the input list.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…