Rory Zipher
Rory Zipher

Reputation: 255

Python sorting by three criteria

I'm trying to get a handle on sorting by several criteria (length, suffix and alphabetically in that order). I can't quite get a grip on it though, and all I seem to be able to do is sort by length...

Here's my code (python 2.7.9):

#!/usr/bin/python

sortme = [
    'one.ab',
    'two.ef',
    'three.ab',
    'six.ef',
    'seven.jk',
    'eight.ef',
    'nine.xy',
    'five.xy',
    'ten.ab',
    'Four.ef'
]

sortme.sort(key=lambda item: (-len(item), item), reverse=True)

print(sortme)

This gets the length part, but I'm really trying to get:

(ab)
one.ab
ten.ab
three.ab

(ef)
six.ef
two.ef
four.ef
eight.ef

(jk)
seven.jk

(xy)
five.xy
nine.xy

Upvotes: 0

Views: 176

Answers (3)

SatanDmytro
SatanDmytro

Reputation: 537

You can also try cmp function:

import re


sortme = [
    'one.ab',
    'two.ef',
    'three.ab',
    'six.ef',
    'seven.jk',
    'eight.ef',
    'nine.xy',
    'five.xy',
    'ten.ab',
    'Four.ef'
]

def _cmp(first, second):
    first_type = first.split('.')[-1]
    second_type = second.split('.')[-1]
    if first_type == second_type:
        return cmp(len(first), len(second))

    return cmp(first_type, second_type)

sortme.sort(cmp=_cmp)

print(sortme)

Upvotes: 0

GWW
GWW

Reputation: 44093

You can specify multiple sort keys as a tuple:

sortme.sort(key=lambda item: (item.split('.')[1], len(item), item), reverse=False)

print("\n".join(sortme))

Output:

one.ab
ten.ab
three.ab
six.ef
two.ef
Four.ef
eight.ef
seven.jk
five.xy
nine.xy

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113988

sortme.sort(key=lambda item: (-len(item),item.rsplit(".",1)[-1], item), reverse=True)

you just add your 3rd criteria ... I would really recommend sitting down with a tutor or your teacher.

you can always break it off into its own funtion to make it more understandable

def sort_key(item):
    return -len(item),item.rsplit(".",1)[-1],item

sortme.sort(key=sort_key,reverse=True)

Upvotes: 0

Related Questions