Sort list of list with custom compare function in Python
By : Vinod Kumar Vinod
Date : March 29 2020, 07:55 AM
Does that help I know there are several questions named like this, but I can't seems to get their answers to work. code :
>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]
|
Sort list of lists using custom compare function python
By : starter
Date : March 29 2020, 07:55 AM
I hope this helps . I was trying to sort list of lists in python but it doesn't seem to work. , You don't need cmp here just use a key :
|
Why must std::sort compare function return false when arguments are equal?
By : kapil
Date : March 29 2020, 07:55 AM
Does that help The compare function simply models a "less than" operator. Consider how the < operator works for primitive types like int:
|
Python sort list by function with multiple arguments
By : odockbond
Date : March 29 2020, 07:55 AM
Hope that helps There are several ways you can do this. Assume we have a list lst. Set default values code :
def func(x, y=1, z=2):
return x + y + z
res = sorted(lst, key=func)
from functools import partial
def func(x, y, z):
return x + y + z
res = sorted(lst, key=partial(func, y=1, z=2))
def func(x, y, z):
return x + y + z
res = sorted(lst, key=lambda x: func(x, x+1, x+2))
|
specifying arguments to the compare function in C++ sort
By : Julien Bedier
Date : September 28 2020, 03:00 AM
will be helpful for those in need My question is how the compare function in the C++ sort function takes parameters. if I want to sort an array but also want to preserve the index of the elements i thought of sorting the index array based on the elements in the actual array. The issue is i am not able to find how to pass the parameters to the compare function. suppose the array is 3 5 4 2 indexes are 0 1 2 3 . I want the index array output 3 0 2 1 which is 2 3 4 5 . how can i do that using the sort function. , One way to do it : code :
vector<int> data{ 3, 5, 4, 2 },
index{ 0, 1, 2, 3 };
sort(index.begin(), index.end(), [&data](int i, int j) { return data[i] < data[j]; });
for (int i : index)
{
cout << i << ' ';
}
|