移动lis的最后一个元素

2024-03-29 11:35:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 方法元素列表forlenreturnifdef
3条回答

从列表中弹出项目,并使用^{}将其插回:

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

不如@Ashwini的答案那么性感,但你可以试试这个。你知道吗

而不是:

    lst[i] = last

(向下移动时,将用最后一个值覆盖整个数组)

请执行以下操作:

    lst[i+1] = lst[i]

(这将使所有值都发生偏移)

在所有的循环之后:

    lst[i+1] = last

(将最后一个值放在正确的位置,即i+1的位置)

适当的方法是插入排序算法,但现在我们只对最后一项进行排序,所以,这里是:

list = [1, 3, 4, 5, 6, 2] # our list
item = list[len(list)-1] # last element
i = len(list)-2 # the starting element to compare the last element to
while item<list[i] and i>=0: # while place not found and index in range
    list[i+1]=list[i] # move element at i to i+1
    i-=1 # decrement i, so to compare with next left element
list[i+1]=item # when the loop is completed, we then have our last item's position in i+1
print(list) # this prints [1, 2, 3, 4, 5, 6]


您可以阅读更多关于插入排序算法的内容,这里的解释有点棘手,我的意思是它需要一个很长的解释和示例,因此,您可以在Wikipedia上看到更多:https://en.wikipedia.org/wiki/Insertion_sort

相关问题 更多 >