我正在寻找一种有效的方法将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]

最佳答案

从列表中弹出项目并使用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]

09-09 21:55
查看更多