This question already has answers here :
You can use the python sorting functions' key
parameter to sort the index array instead.
>>> s = [2, 3, 1, 4, 5]
>>> sorted(range(len(s)), key=lambda k: s[k])
[2, 0, 1, 3, 4]
>>>
11 Answers You sort the list by passing it to sorted and specifying a function to extract the sort key (the second element of each tuple; that's what the lambda is for. Finally, the original index of each sorted element is extracted using the [i[0] for i in ] list comprehension. and from the sorted list fetch all the indexes from the dictionary. Something like : a = [2,3,1,4,5] b = list (a) b.sort () b [1, 2, 3, 4, 5] indexDict = dict ( [ (value, index) for index, value in enumerate (a)]) [indexDict [entry] for entry in b] [2, 0, 1, 3, 4] HTH.
You can do this with numpy's argsort method if you have numpy available:
>>> import numpy
>>> vals = numpy.array([2,3,1,4,5])
>>> vals
array([2, 3, 1, 4, 5])
>>> sort_index = numpy.argsort(vals)
>>> sort_index
array([2, 0, 1, 3, 4])
If not available, taken from this question, this is the fastest method:
>>> vals = [2,3,1,4,5]
>>> sorted(range(len(vals)), key=vals.__getitem__)
[2, 0, 1, 3, 4]
Sort a list in python and then return the index of elements in sorted order. Examples: Input : [2, 3, 1, 4, 5] Output : [2, 0, 1, 3, 4] After sorting list becomes [1, 2, 3, 4, return a descending sorted list of country names based on the values in a row using an array formula that itself makes use of Excel's INDEX, MATCH, RANK, COLUMN and COLUMNS functions. Using an array formula, return a descending sorted list of country names based on the values in a row.
If you need both the sorted list and the list of indices, you could do:
L = [2,3,1,4,5]
from operator import itemgetter
indices, L_sorted = zip(*sorted(enumerate(L), key=itemgetter(1)))
list(L_sorted)
>>> [1, 2, 3, 4, 5]
list(indices)
>>> [2, 0, 1, 3, 4]
Or, for Python <2.4 (no itemgetter
or sorted
):
temp = [(v,i) for i,v in enumerate(L)]
temp.sort
indices, L_sorted = zip(*temp)
p.s. The zip(*iterable)
idiom reverses the zip process (unzip).
Update:
To deal with your specific requirements:
"my specific need to sort a list of objects based on a property of the objects. i then need to re-order a corresponding list to match the order of the newly sorted list."
That's a long-winded way of doing it. You can achieve that with a single sort by zipping both lists together then sort using the object property as your sort key (and unzipping after).
combined = zip(obj_list, secondary_list)
zipped_sorted = sorted(combined, key=lambda x: x[0].some_obj_attribute)
obj_list, secondary_list = map(list, zip(*zipped_sorted))
Here's a simple example, using strings to represent your object. Here we use the length of the string as the key for sorting.:
str_list = ["banana", "apple", "nom", "Eeeeeeeeeeek"]
sec_list = [0.123423, 9.231, 23, 10.11001]
temp = sorted(zip(str_list, sec_list), key=lambda x: len(x[0]))
str_list, sec_list = map(list, zip(*temp))
str_list
>>> ['nom', 'apple', 'banana', 'Eeeeeeeeeeek']
sec_list
>>> [23, 9.231, 0.123423, 10.11001]
We can sort list of list using the conventional sort function. can be circumstances that requires the sorting of list of list by other index elements than first. Python | Subgroups of i'th index size in list · Python | Returning index of a sorted list Convert your list into a new list of pairs (object, original index of object). Sort the new list by the first item in the pair Extract the sorted list and the original indices. Here's some code to demonstrate the principle:
How about
l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]
Returns the zero-based index of the specified key in a SortedList object. public: virtual int IndexOfKey(System::Object ^ key);. C# Copy. What is the best way in R to return the indices for the sorted array elements from the original array. I'm looking for an output like : 6(index of 2), 4(index of 3), 3(index of 4), 2(index of 7), 5(index of 8), 1(index of 10)
you can use numpy.argsort
or you can do:
test = [2,3,1,4,5]
idxs = list(zip(*sorted([(val, i) for i, val in enumerate(test)])))[1]
zip
will rearange the list so that the first element is test
and the second is the idxs
.
Variant of sort! that returns a sorted copy of v leaving v itself unmodified. at a time, inserting each element into its correct, sorted position in the output list. Return the index of the first value in a greater than or equal to x , according to the index () is an inbuilt function in Python, which searches for given element from start of the list and returns the lowest index where the element appears. element - The element whose lowest index will be returned. start (Optional) - The position from where the search begins. end (Optional) - The position from where the search ends.
Sorting is a very important concept when writing algorithms. There are all kinds of sorts: bubble sort, shell sort, block sort, comb sort, cocktail The index() method searches an element in the list and returns its index. In simple terms, the index() method finds the given element in a list and returns its position. If the same element is present more than once, the method returns the index of the first occurrence of the element.
list.sort(). The sort function returns a sorted array by doing in-place This function in numpy returns the indices of the sorted array instead of the The sorted() function returns a sorted list from the items in an iterable. The sorted() function sorts the elements of a given iterable in a specific order (either ascending or descending ) and returns the sorted iterable as a list.
how to arrange the values in ascending order along with its corresponding index change ? what is the command for this ? help me out ! 0 Comments. and returns H in cell G5. Download excel *.xlsx file. Lookup and return multiple values sorted in a custom order.xlsx. Functions in this post. IF(logical_test, [value_if_true], [value_if_false]) Checks whether a condition is met, and returns one value if TRUE, and another value if FALSE. SMALL Returns the k-th smallest number in this data set.
Comments One option could be to map the list of objects to a list of tuples [obj1, obj2, ...]
-> [(0,obj1), (1, obj2), ...]
and sort this list. Then you have the new order of the original indexes right away. You don't really need the indices to sort the corresponding list. Just zip the list together before sorting, then unzip. (Updated my answer with an example). @FelixKling You'd need to do that, and specify the sort key to be the second element of the tuple. @sykora: Of course, but I thought OP is specifying a key anyway, as the objects are sorted by a certain property... Related: stackoverflow.com/questions/6422700/… Very nice. So the NumPy version is faster than the sorted(...)
version? For large arrays, yes. This is O(n^2)
...