sort help

Peter Otten __peter__ at web.de
Wed Sep 23 03:05:25 EDT 2015


Larry Martell wrote:

> I currently have 3 lists of lists and I sort them based on a common
> field into a single list like this:
> 
>         def GetObjKey(a):
>             return a[2]
> 
>         sorted(a + b + c, key=GetObjKey)
> 
> Which works just fine.
> 
> But now, I need to have just the first list (a) also sub sorted by
> another field and I can't quite figure out how to do this.
> 
> So for example, if my initial data was this (I'll only show the fields
> involved with the sort - the first number is a[2] above and the second
> is the new additional sorting field, only present in a)
> 
> a[1, 4]
> a[1, 2]
> a[2, 3]
> a[2, 1]
> a[5, 6]
> a[5, 2]
> b[2]
> b[5]
> c[1]
> c[6]
> 
> Then I'd want my sorted list to be this:
> 
> a[1,2]
> a[1,4]
> c[1]
> a[2,1]
> a[2,3]
> b[2]
> a[5,2]
> a[5,6]
> b[5]
> c[6]
> 
> I hope that's clear.
> 
> So is there some pythonic way to sort this without resorting to a
> brute force old fashioned plow through the data?

Performing two sorts as suggested by Chris and Paul is cleaner, but it is 
possible to write the key function you were probably looking for.

def get_obj_key(a):
    if has_extra_field(a):
        return a[2], 0, a[-1] # assuming a[-1] is the extra field
    else:
        return a[2], 1

You have to write the has_extra_field() test yourself as I don't know what 
distinguishes the items in a from those in the other sequences. For example:

>>> a = [[1, 4], [1, 2], [2, 3], [2, 1], [5, 6], [5, 2]]
>>> b = [[2], [5]]
>>> c = [[1], [6]]
>>> sorted(a + b + c,
... key=lambda a: (a[0], 0, a[-1]) if len(a) > 1 else (a[0], 1))
[[1, 2], [1, 4], [1], [2, 1], [2, 3], [2], [5, 2], [5, 6], [5], [6]]





More information about the Python-list mailing list