Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort by one element in list of lists of fixed size and remove doubles

I would like to find the best way to achieve this. (I already can do it manually but i am looking for a librairy that do this directly).

I want to sort a list of lists based on the first index and remove doubles of first index.

sections = [
    [1, 4, 1],
    [5, 3, 2],  # Sort on the first element of sublist
    [2, 2, 3],
    [2, 1, 4],  # Double to remove
]

assertion = [
    [1, 4, 1],
    [2, 2, 3],
    [5, 3, 2],
]

def sort_first_and_remove_double(sections):
    
    return result


assert sort_first_and_remove_double(sections) == assertion

The goal is to not coding any loop directly but do it in one or two lines using librairies, for optimisation reasons, my datas are huges.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My attempt code is here:

def sort_first_and_remove_double(sections):
    sections = remove_double(sections)
    sections = sort_sections(sections)
    return sections


def sort_sections(sections):
    ids = get_ids(sections)
    return [x for _, x in sorted(zip(ids, sections))]


def remove_double(sections):
    ids = get_ids(sections)
    keeped_sections = []
    for i, id_check in enumerate(ids):
        ids_keeped = get_ids(keeped_sections)
        if id_check not in ids_keeped:
            keeped_sections.append(sections[i])
    return keeped_sections


def get_ids(sections):
    return [section[0] for section in sections]

But it is very slow!

>Solution :

Are you wont solution like this?

sorted({x[0]: x for x in sections[::-1]}.values())

or without for

sorted(dict(map(lambda x: (x[0], x), sections[::-1])).values())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading