0

for example if we have l=[[0,1,2],[3,4,5,6],[4,5,6]] since the list [3,10,11] is of bigger size we can sort and return result as l=[[0,1,2], [4,5,6], [3,4,5,6]] now if we append [1] to list it gives==> [[1],[0,1,2],[4,5,6],[3,4,5,6]] basically i am saying that like in bisect.insort(list,element) it automatically inserts the element at its correct position by using sorting methods but here i like to insert the element in terms of length.

if i explain more clearly then if you are a c++ user then

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;

I want this type of thing in python

JohnFilleau
  • 4,045
  • 1
  • 15
  • 22
prakhar newatia
  • 169
  • 2
  • 3

4 Answers4

1

The key parameter to the list.sort() function specifies a one-argument function that takes each item in the list and returns its sorting key.

If you want your elements to be sorted on size, and then lexicographically, it's as easy as setting the key for each sublist, l, to be [len(l), l]. Sorting will then be done by comparing the first elements (integers), with lower occurring first. If the lengths are equal, then the lists themselves will be compared lexicographically.

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

JohnFilleau
  • 4,045
  • 1
  • 15
  • 22
0

Unfortunately Python has no sorted containers, so there is no built-in equivalent of std::set as in C++.

However, you may want to try out the sortedcontainer module, which may help, but not at the order you mentioned because in python, [0,1,2] < [1].

adrtam
  • 6,991
  • 2
  • 12
  • 27
0

There might be an easier way to do this (or maybe I don't understand the question), by this would work:

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

Or if you do it regularly:

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

mylist = add_sort(mylist, [1])

Note that this doesn't sort by the numbers, only by the length of the lists. I.e., you can get the result:

#[[8], [1], [1, 2], [6, 7], [3, 4, 5]]
Taren Sanders
  • 421
  • 2
  • 12
0

There is library in python which is bisect

import bisect

now if we use bisect.insort(list,element) everytime to insert an element, it will insert in a sorted order only

prakhar newatia
  • 169
  • 2
  • 3