移动列表的最后一个元素

Mil*_*vic 1 python arrays sorting algorithm array-algorithms

我正在寻找将python中列表的最后一个元素移动到适当位置的有效方法.例如,如果我们有list = [1,3,4,5,6,2],我们应该得到list = [1,2,3,4,5,6].我尝试的方法并不适用于理想的方式:

    def sort1(lng, lst):
        if len(lst) != lng:
            return
        else:
            i = -2
            last = lst[-1]
            for x in lst:
                if last < lst[i]:
                    lst[i] = last
                    i -= 1
                    print(lst)
    sort1(6,[1,3,4,5,6,2])


It is giving me following result:
   [1, 3, 4, 5, 2, 2]
   [1, 3, 4, 2, 2, 2]
   [1, 3, 2, 2, 2, 2]
   [1, 2, 2, 2, 2, 2]
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 6

弹出列表中的项目并使用bisect.insort_left以下命令将其插入:

>>> import bisect
>>> lst = [1, 3, 4, 5, 6, 2]
>>> item = lst.pop()
>>> bisect.insort_left(lst, item)
>>> lst
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)