【问题标题】:In python is there a method to have a list of list which remains sorted in terms of length?在 python 中,有没有一种方法可以让列表保持按长度排序?
【发布时间】:2020-08-31 20:24:10
【问题描述】:

例如,如果我们有l=[[0,1,2],[3,4,5,6],[4,5,6]],因为列表[3,10,11] 更大,我们可以排序并返回结果为l=[[0,1,2], [4,5,6], [3,4,5,6]] 现在,如果我们将 [1] 附加到列表中,它会给出==> [[1],[0,1,2],[4,5,6],[3,4,5,6]] 基本上我的意思是,就像在bisect.insort(list,element) 中一样,它通过使用排序方法自动将元素插入到正确的位置,但在这里我喜欢根据长度插入元素。

如果我解释得更清楚,那么如果你是 c++ 用户,那么

struct cmp {
    bool operator() (const pair<int, int> &a,
                     const pair<int, int> &b) const {
        int lena = a.second - a.first + 1;
        int lenb = b.second - b.first + 1;
        if (lena == lenb) return a.first < b.first;
        return lena > lenb;
    }
};  
set<pair<int, int>, cmp> segs;

我想要这种类型的东西在 python

【问题讨论】:

    标签: python sorting data-structures


    【解决方案1】:

    list.sort() 函数的 key 参数指定了一个单参数函数,该函数接受列表中的每个项目并返回其排序键。

    如果您希望元素按大小排序,然后按字典顺序排列,只需将每个子列表的键 l 设置为 [len(l), l] 即可。然后将通过比较第一个元素(整数)来完成排序,首先出现较低的元素。如果长度相等,则列表本身将按字典顺序进行比较。

    >>> def list_comp(l):
    ...     return [len(l), l]
    ... 
    >>> l = [[7,], [2,], [], [0, 1, 1], [0, 0, 1], [4, 5, 6, 7], [8, 9, 10, 11], [5,]]
    >>> l.sort(key=list_comp)
    >>> l
    [[], [2], [5], [7], [0, 0, 1], [0, 1, 1], [4, 5, 6, 7], [8, 9, 10, 11]]
    >>> 
    
    

    【讨论】:

      【解决方案2】:

      不幸的是 Python has no sorted containers,因此没有像 C++ 中那样内置的 std::set 等价物。

      但是,您可能想尝试 sortedcontainer 模块,这可能会有所帮助,但不是按照您提到的顺序,因为在 python 中,[0,1,2] &lt; [1]

      【讨论】:

        【解决方案3】:

        可能有一种更简单的方法可以做到这一点(或者我可能不明白这个问题),这样可以:

        mylist = [[1,2], [3,4,5],[6,7],[8]]
        mylist
        # [[1, 2], [3, 4, 5], [6, 7], [8]]
        
        mylist.append([9])
        mylist = sorted(mylist, key=len)
        mylist
        # [[8], [9], [1, 2], [6, 7], [3, 4, 5]]
        

        或者如果你经常这样做:

        def add_sort(mylist, newitem):
            mylist.append(newitem)
            return sorted(mylist, key=len)
        
        mylist = add_sort(mylist, [1])
        

        请注意,这不是按数字排序,而是按列表的长度排序。即,你可以得到结果:

        #[[8], [1], [1, 2], [6, 7], [3, 4, 5]]
        

        【讨论】:

          【解决方案4】:

          python中有一个库是bisect

          导入二分法

          现在如果我们每次使用 bisect.insort(list,element) 插入一个元素,它只会按排序顺序插入

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-03-08
            • 1970-01-01
            • 2020-02-10
            • 1970-01-01
            • 2012-09-15
            • 2023-03-15
            相关资源
            最近更新 更多