Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #97002 > unrolled thread

sort help

Started byLarry Martell <larry.martell@gmail.com>
First post2015-09-22 18:42 -0400
Last post2015-09-22 19:40 -0700
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python


Contents

  sort help Larry Martell <larry.martell@gmail.com> - 2015-09-22 18:42 -0400
    Re: sort help Paul Rubin <no.email@nospam.invalid> - 2015-09-22 19:40 -0700

#97002 — sort help

FromLarry Martell <larry.martell@gmail.com>
Date2015-09-22 18:42 -0400
Subjectsort help
Message-ID<mailman.74.1442962283.28679.python-list@python.org>
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?

[toc] | [next] | [standalone]


#97014

FromPaul Rubin <no.email@nospam.invalid>
Date2015-09-22 19:40 -0700
Message-ID<87io71dfjy.fsf@jester.gateway.sonic.net>
In reply to#97002
Larry Martell <larry.martell@gmail.com> writes:
>         def GetObjKey(a):
>             return a[2]

This function is called operator.itemgetter:

    from operator import itemgetter
    sorted(a + b + c, key=itemgetter(2))

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

  sorted(sorted(a, key=itemgetter(5)) + b + c, key = itemgetter(2))

or whatever the new field (instead of 5) is for a.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web