for循环在lis数字排序中的应用

2024-10-04 05:23:06 发布

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

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])) 

Tags: toinaddforreturnifdefneed
2条回答

使用来自这个question的对分将是解决问题的好方法。另见wikipedia。但一个简单的例子是:

def Insert(val, list):
    for i, entry in enumerate(list):
        if val < entry:
            return list[0:i] + [val] + list[i:]
print(Insert(6,[2,4,5,7,8]));

为什么要编写复杂的代码插入到排序列表中?您可以使用以下内容:

>>> x = [2,4,5,7,8]
>>> x.append(6)
>>> x.sort()
>>> x
[2, 4, 5, 6, 7, 8]

除非遇到巨大的性能瓶颈,否则最好只使用该语言的特性。我喜欢称之为开发工作的优化。你知道吗

相关问题 更多 >