def insert3(x,ss):
left = [] #why this need to add properly by list, or not it just return the recent result.
while ss!= []:
for y in ss:
if x<= ss[0]:
return left + [x] + ss[0:]
else:
ss, left = ss[1:], left + [ss[0]]
return left + ss + [x]
print(insert3(6,[2,4,5,7,8]))
这是该函数的 for 循环的正确用法吗?
我改变了一点。这是正确的吗?
def insert3(x,ss):
left = []
for y in ss:
if x<= ss[0]:
return left + [x] + ss[0:]
else:
ss, left = ss[1:], left + [ss[0]]
return left + ss + [x]
print(insert3(6,[2,4,5,7,8]))
最佳答案
为什么要编写复杂的代码来插入排序列表?你可以使用类似的东西:
>>> x = [2,4,5,7,8]
>>> x.append(6)
>>> x.sort()
>>> x
[2, 4, 5, 6, 7, 8]
除非遇到巨大的性能瓶颈,否则最好只使用该语言的功能。我喜欢称之为开发工作优化。
关于python - 使用 for 循环对列表中的数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33019677/