【问题标题】:Python sort none ignore (or stable)Python排序无忽略(或稳定)
【发布时间】:2018-08-26 21:29:42
【问题描述】:

我的列表中的项目要么是数字要么是None

我想对它们进行排序,以便None 项保持在同一个位置,而对数值进行排序。

例如,我想要这个列表:

[None, None, 20, None, 10]

待分类:

[None, None, 10, None, 20]

还有这个:

[None, 50, 20, None, None]

进入:

[None, 20, 50, None, None]

【问题讨论】:

    标签: python sorting nonetype


    【解决方案1】:

    你可以像这样获得你的稳定排序:

    • 先对非None的值进行排序
    • 然后创建输出列表:
      • 如果原始列表项为无,则输出项为无
      • 如果是数值,我们取排序列表中的下一个值

    通过在其上创建一个迭代器,然后在其上调用next,可以轻松地从排序列表中获取下一个值。


    def stable_sort(lst):
        sorted_values = sorted([value for value in lst if value is not None])
        it_sorted = iter(sorted_values)
        out = []
        for value in lst:
            out.append(None if value is None else next(it_sorted))
        return out
    
    print(stable_sort([None, None, 20, None, 10]))
    # [None, None, 10, None, 20]
    
    print(stable_sort([None, 50, 20, None, None]))
    # [None, 20, 50, None, None]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 2015-06-02
      • 2016-05-23
      相关资源
      最近更新 更多