generic xmerge ?

Alex Martelli aleaxit at yahoo.com
Mon Oct 17 07:03:16 EDT 2005


bonono at gmail.com <bonono at gmail.com> wrote:

> Hi,
> 
> I was reading this recipe and am wondering if there is a generic
> version of it floating around ? My list is a tuple (date, v1, v2, v3)
> and I would like it to sort on date. The documentation doesn't mention
> how the items are compared and the example only use integers.
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/141934

I'm not sure what "my list is a tuple" mean (list and tuple being
different types) nor what this has to do with the recipe.  Anyway...
sequences are compared lexicographically -- first items first, then
second items if the first items are equal, and so on.  So, if you have a
list X whose items tuples and want X sorted on the tuples' first items,
X.sort() will suffice -- if the tuples never have equal first-items, or
if you're OK with second-items getting compared when the first-items are
equal.  If you want to sort on first-items ONLY, leaving the tuples in
the same order in the list when their first-items are equal:

import operator
X.sort(key=operator.itemgetter(0))


Alex



More information about the Python-list mailing list