Ask
Ask

Reputation: 27

Sorting list of lists by the first list

I currently have a small script written which takes four lists, where, for instance, every 0'th index matches each other. I sort these lists by the first list, while the other lists are sorted in the same pattern. Like so:

Unsorted lists:

list0: 4, 2, 1, 3

list1: four, two, one, three

Sorted lists:

list0: 1, 2, 3, 4

list1: one, two, three, four

This works with the following script:

list0=IN[0]
list1=IN[1]
list2=IN[2]
list3=IN[3]

list0,list1,list2,list3 =zip(*sorted(zip(list0,list1,list2,list3)))

list0,list1,list2,list3 = (list(t) for t in zip(*sorted(zip(list0,list1,list2,list3))))


#Output:
OUT = [list0,list1,list2,list3]

I want to be able to convert this to a more general script with any number of lists. Thus, my input would be a list of lists, and they should be sorted like shown in the code above. Can you help me out?

Best regards,

Ask

Upvotes: 1

Views: 110

Answers (2)

user10325516
user10325516

Reputation:

One more answer to the question:

list_of_lists = [
    [1, 2, 3, 0],
    [1, 2, 3, 4],
    [5, 6, 7, 8]]

dict_of_lists = {
    'a': [1, 2, 3, 0],
    'b': [1, 2, 3, 4],
    'c': [5, 6, 7, 8]}


def sort_list_of_lists(lst, idx):
    # idx - is index of list to use for sorting all the lists
    return list(list(tup) for tup in zip(*sorted(zip(*lst), key=lambda x: x[idx])))


def sort_dict_of_lists(dct, key):
    # key - is key of list to use for sorting all the lists
    keys = list(dct.keys())
    # get list from dict
    lst = [dct[key_] for key_ in keys]
    # get idx from key
    idx = keys.index(key)
    # use function 'sort_list_of_lists' for actual sorting
    return {key_: lst_ for key_, lst_ in zip(keys, sort_list_of_lists(lst, idx))}


sorted_list_of_lists = sort_list_of_lists(list_of_lists, idx=0)
sorted_dict_of_lists = sort_dict_of_lists(dict_of_lists, key='a')

If I met the problem like this I would use pandas to solve it - very convenient and efficient tool to handle tables:

import pandas as pd

dataframe_from_list = pd.DataFrame(list_of_lists).T
dataframe_from_dict = pd.DataFrame(dict_of_lists)

dataframe_from_list.sort_values(by=0, inplace=True)
dataframe_from_dict.sort_values(by='a', inplace=True)

Upvotes: 0

Ivan De Paz Centeno
Ivan De Paz Centeno

Reputation: 3775

Is this what you are looking for?

def sort_lists(*args):
    zipped_list = zip(*sorted(zip(*args)))
    return [list(l) for l in zipped_list]

Example:

>>> l1 = [4,2,1,3]
>>> l2 = ["four", "two", "one", "three"]
>>> sort_lists(l1, l2)
[[1, 2, 3, 4], ['one', 'two', 'three', 'four']]

Based on your code example, you could use it as follows:

>>> OUT = sort_lists(*IN)

Upvotes: 1

Related Questions