【发布时间】:2015-01-28 14:48:53
【问题描述】:
我正在寻找将 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]
【问题讨论】:
-
您在搜索
lst.sort()吗? -
list.insert可能对你有用。
标签: python arrays algorithm sorting array-algorithms