首页 > 解决方案 > 向左旋转数组

问题描述

我正在尝试使用以下函数来旋转数组:

def rotLeft(a,d):
    temp=[]
    temp.append(a[0:-1])
    temp.insert(0,a[-1])
    return temp

我应该得到输出为 5 1 2 3 4

但我得到 5,[1,2,3,4]

如何解决这个问题呢

标签: pythonarrayspython-3.xlist

解决方案


您必须使用 Use.extend()而不是.append()as.append().insert()is 来添加元素,而.extend()is 合并两个列表:

def rotLeft(a,d):
    temp=[]
    temp.extend(a[0:-1])
    temp.insert(0,a[-1])
    return temp

print(rotLeft([1,2,3,4,5], 1))

输出:

[5, 1, 2, 3, 4]

推荐阅读