Python Forum
How to sort a list with duplicates and return their unique indices.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to sort a list with duplicates and return their unique indices.
#4
I think DeaD_EyE is not interpreting the question correctly. I do not think "unique" means that the lst should be pared down to only contain unique values. I think the problem is the way the index sort was done returned non-unique values. The problem is caused by using "index" which returns the first match, not the index of the element.

To solve the problem, create a list of index values, and sort these using a key that references the original list. This is what perfingo did with the index, value tuples. Another way to do the same thing is create a separate list of index values and sort the index list using a key that references the original list.
lst = [48,52,35,35,44,35]
index = range(len(lst))
sorted_index = sorted(index, key=lambda i: lst[i])
print(sorted_index)
I like perfingo's method because it produces the sorted list and the sorted index list at the same time. I would use that if I needed both results. If I only needed the sorted index list I might use the separate array.

You could also do this with numpy's argsort()
import numpy as np

lst = np.array([48,52,35,35,44,35])
print(lst.argsort())
Reply


Messages In This Thread
RE: How to sort a list with duplicates and return their unique indices. - by deanhystad - Sep-23-2022, 07:53 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  help with adding duplicates elements together in a list 2ECC3O 5 2,015 Sep-10-2022, 07:11 AM
Last Post: 2ECC3O
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 6,356 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  how to sort a list without .sort() function letmecode 3 3,419 Dec-28-2020, 11:21 PM
Last Post: perfringo
  Dealing with duplicates to an Excel sheet DistraughtMuffin 6 3,256 Oct-28-2020, 05:16 PM
Last Post: Askic
  Get 5 most unique combinations of elements in a 2D list wanttolearn 1 2,298 Sep-24-2020, 02:26 PM
Last Post: buran
  Return the sum of the first n numbers in the list. pav1983 3 4,045 Jun-24-2020, 03:37 AM
Last Post: deanhystad
  How can I print the number of unique elements in a list? AnOddGirl 5 3,249 Mar-24-2020, 05:47 AM
Last Post: AnOddGirl
  duplicates nsx200 3 2,418 Nov-12-2019, 08:55 AM
Last Post: nsx200
  Exercise list remove duplicates RavCOder 9 5,235 Oct-23-2019, 04:16 PM
Last Post: jefsummers
  list and sort query arian29 2 2,214 Sep-18-2019, 06:19 PM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020