1

I'm currently new to python and got stuck at this question, can't seem to find the proper answer.

I have a list contain :

BLUE
BLUE-ELMWOOD-CAMO
BLUE-MIST
BLUE-MIST-SPRING-LEAF
BLUE-MULTI
BOTTLE-GREEN
CABANA-BLUE
CAPRI-NAVY

And I want to sort like this :

BLUE-ELMWOOD-CAMO
BLUE-MIST-SPRING-LEAF
BLUE-MIST
BLUE-MULTI
BLUE
BOTTLE-GREEN
CABANA-BLUE
CAPRI-NAVY

Like this:

enter image description here

I've tried list.sort() but it gives the first one

Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
  • 2
    https://stackoverflow.com/questions/42899405/sort-a-list-with-longest-items-first has some solutions to try. – bbayles May 05 '20 at 15:59
  • So its alphabetical for first word then total length ? Why BLUE-MULTI is after BLUE-MIST ? – azro May 05 '20 at 16:41
  • @RyanSchaefer yep `values.sort(key = lambda x: (x.split("-")[0], -len(x)))` is the one – azro May 05 '20 at 16:41
  • @azro I believe it’s actually alphabetical of the longest prefix then by length of the remaining. It’s pretty confusing to be honest and I’m not entirely sure it is a consistent rule. So all have “BLUE” in the first “group”. Regular “BLUE” is then “disqualified” as it isn’t longer than any other word with the same prefix. Then E comes first alphabetically. Then the next two match until most wherein the length breaks the tie. Then “MULTI” comes after that. The author would have to be more specific for the tie breakers here I think. – Ryan Schaefer May 05 '20 at 16:47

0 Answers0