Link to home
Create AccountLog in
Avatar of Isaiah Melendez
Isaiah Melendez

asked on

How can I sort multiple Python lists based on the sort applied to one list?

I have a list of lists in Python that essentially represent a table. I know I should have used a pandas dataframe to accomplish this, but hindsight is 20/20. I digress...below is an example list of what I'm talking about.

The overarching list variable is comprised of these nested lists:

['Store number', 2, 3, 4, 1, 5]
['Variable 1', 82, 99, 44, 32, 65]
['String 1', 'cat', 'dog', 'lizard', 'alligator', 'crocodile']

In the current state, each index of each nested list corresponds to the same row in the table. So for store number 2, variable 1 is 82 and string 1 is cat. Say I want to sort each list to where these relationships are maintained, but we sort by ascending store number. The final lists would look like:

['Store number', 1, 2, 3, 4, 5]
['Variable 1', 32, 82, 99, 44, 65]
['String 1', 'alligator', 'cat', 'dog', 'lizard', 'crocodile']

How could I accomplish this using my current data structures?
Avatar of dpearson
dpearson

You have two options.  
a) You can add a data structure that links these lists together (e.g. a list of maps that connect up the entries) and then sort that based on the first field.  But it sounds like you don't want to add days structures.

b) You can implement a simple sort and when this sort moves an item in the first list, you move the matching ones.

E.g. Bubble sort is a very simple sort to implement.  You just loop through all items in the list and compare n to n+1.  If the two items aren't in the correct order you swap them (and in your case swap the items in the other two lists as well at the same positions).  You also record that a swap was made (just a boolean flag).

Then after going through the whole list, check to see if any swaps were made.  If some were swapped, repeat the whole process.  If not, the list (and the matching ones) will all now be sorted.

It's not the fastest sort, but it is simple to implement and will solve this problem.
You mention you use pandas.... So why not use the padas sorting functions for dataframes:
See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html
ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account