python - 使用 for 循环对列表中的数字进行排序

标签 python sorting for-loop

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/

相关文章:

ios - 按编号对解析对象进行排序

R graph 仅针对指定级别按级别重新排序因子

python - Python 3 中的用户输入和排序列表

javascript - 如何使 jQuery 方法在 for 循环中工作?

Python/Tkinter - 将文本框的背景变成图像?

Python 安装工具 : first build from sources then install

python - python Flask应用程序中使用json对象上传文件的POST方法

python - Selenium/Python - 如何模拟服务器响应?

Java for循环迭代和循环多个变量直到满足条件

r - 如何使用 R 和 ggplot2 创建绘图矩阵