小编Mil*_*vic的帖子

移动列表的最后一个元素

我正在寻找将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)

python arrays sorting algorithm array-algorithms

1
推荐指数
1
解决办法
136
查看次数

标签 统计

algorithm ×1

array-algorithms ×1

arrays ×1

python ×1

sorting ×1