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.

Recommended Answers

All 6 Replies

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])

Thanks Mitk, your a legend ;)

You're welcome.
PS: My name is Mitko ;)

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:

I've just started learning Python :icon_cool:

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.