Hi guys,

Quick question. Im having some problems with advanced sorting.

Say i have the following list:
[number] + [text]
3 text_red
7 text_yellow
9 text_blue
1 text_pink
3 text_black
6 text_orange
7 text_white

Firstly the list needs to be ordered via the number at the front of the list (which was determined by a function and added to another function to create [number] + [text]). Then, if the [number] is the SAME as another [number], it needs to be ordered in the ORIGINAL ORDER.

So, the order required is:
1 text_pint
3 text_red
3 text_black
6 text_orange
7 text_yellow
7 text_white
9 text_blue

any help would be greatly appriciated.

Hi.

If you have a list like that :

listunsorted = ['3 text_red','7 text_yellow','9 text_blue', '1 text_pink','3 text_black','6 text_orange','7 text_white']

... you can sort it like this :

listsorted =sorted(listunsorted, key=lambda x: x.split()[0])

Nice solution Mitko, can even be made mildly simpler:

listsorted = sorted(listunsorted, key=lambda x: x[0])

I've just started learning Python :icon_cool:

Welcome to the DaniWeb Python community, looks like you are doing great.

This question has already been answered. Start a new discussion instead.