【问题标题】:Python - How to append integer in list and to sort? [duplicate]Python - 如何在列表中附加整数并进行排序? [复制]
【发布时间】:2017-12-02 21:50:44
【问题描述】:

我想追加到列表中并进行排序

例如

num_list = [5, 10, 15, 20]
num_list.append(13)
num_list.append(17)

print(num_list)
[5, 10, 13, 15, 17, 20]

【问题讨论】:

  • 使用num_list.sort() 进行排序。
  • 我认为你可以使用任何搜索引擎来找到如何做...
  • 在此处发布您的问题之前您是否搜索过此内容???
  • 对不起,我错过了“同一时间”这个词。我想同时追加和排序

标签: python list


【解决方案1】:

如果您的列表已经排序,您可以直接在正确的位置插入:这会插入并保持列表在 O(n) 中排序。
(感谢@AntonvBR 在 cmets 中的协助)

def insert_sorted(seq, elt):
    """inserts elt at the correct place in seq, to keep it in sorted order
    :param seq: A sorted list
    :param elt: An element comparable to the content of seq
    Effect: mutates the param seq.
    Does not return a result
    """
    idx = 0
    if not seq or elt > seq[-1]:
        seq.append(elt)
    else:
        while elt > seq[idx] and idx < len(seq):
            idx += 1
        seq.insert(idx, elt)

num_list = [5, 10, 15, 20]
insert_sorted(num_list, 21)
num_list

编辑:

您也可以使用模块 bisect,并且这样做可能更有效:(感谢 cmets 中的 @stefan)

import bisect
num_list = [5, 10, 15, 20]
bisect.insort(num_list, 17)

【讨论】:

  • 是的,你是对的,但是即使 bisect 在 log(n) 时间内找到索引,插入也是 O(n)。
  • 很好,谢谢@AntonvBR - 我修好了。
  • @ReblochonMasque 不错,但它现在返回一个副本。需要在 append 或 else 语句后使用 return
  • 又来了!谢谢你。我在演职员表中添加了您的协助。
【解决方案2】:

只需使用bisect.insort() 函数:

import bisect

num_list = [5, 10, 15, 20]
bisect.insort(num_list, 13)
bisect.insort(num_list, 17)

print(num_list)
# [5, 10, 13, 15, 17, 20]

最坏/平均情况O(n) 插入时间复杂度和易于使用。

【讨论】:

    【解决方案3】:

    你可以使用默认的sort方法

        num_list = [5, 10, 15, 20]
        num_list.append(13)
        num_list.append(17)
    
        num_list.sort()
        print(num_list)
    

    【讨论】:

    • 没有必要回答低质量的重复问题
    • 有数千个,而不仅仅是几个元素,因为我想同时追加和排序
    • @ChanghoLee 我们应该猜你想做什么吗? :)
    猜你喜欢
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2016-10-02
    相关资源
    最近更新 更多