Okay, this may not be the smartest idea but I was a bit curious if this is possible. Say I have two lists:
list1 = [3,2,4,1, 1]
list2 = [three, two, four, one, one2]
If I run list1.sort()
, it'll sort it to [1,1,2,3,4]
but is there a way to get to keep list2 in sync as well(so I can say item 4 belongs to 'three')? My problem is I have a pretty complex program that is working fine with lists but I sort of need to start referencing some data. I know this is a perfect situation for dictionaries but I'm trying to avoid dictionaries in my processing because I do need to sort the key values(if I must use dictionaries I know how to use them).
Basically the nature of this program is, the data comes in a random order(like above), I need to sort it, process it and then send out the results(order doesn't matter but users need to know which result belongs to which key). I thought about putting it in a dictionary first, then sorting list one but I would have no way of differentiating of items in the with the same value if order is not maintained(it may have an impact when communicating the results to users). So ideally, once I get the lists I would rather figure out a way to sort both lists together. Is this possible?
I have used the answer given by senderle for a long time until I discovered
np.argsort
. Here is how it works.I find this solution more intuitive, and it works really well. The perfomance:
Even though
np.argsort
isn't the fastest one, I find it easier to use.You can use the key argument in sorted() method unless you have two same values in list2.
The code is given below:
It sorts list2 according to corresponding values in list1, but make sure that while using this, no two values in list2 evaluate to be equal because list.index() function give the first value
You can sort indexes using values as keys:
To get sorted lists given sorted indexes:
In your case you shouldn't have
list1
,list2
but rather a single list of pairs:It is easy to create; it is easy to sort in Python:
Sort by the first value only:
Schwartzian transform. The built-in Python sorting is stable, so the two
1
s don't cause a problem.What about: