list conversion question

Jp Calderone exarkun at divmod.com
Sat Sep 4 19:59:02 CEST 2004


Andrew Dalke wrote:
> Paul McGuire wrote:
> 
>> Assuming im.histogram() returns a list like [ 0, 1, 0, 5, 43, etc. ] how
>> about:
>>
>> hist = [ 0, 1, 0, 5, 43 ]
>> values = [ i for i in enumerate(hist)]
>> values.sort(lambda a,b: cmp(b[1],a[1]))
>> indexes = [ a for a,b in values ]
> 
> 
> or tweaked a bit for speed (a sort with a lambda is expensive)
> and for clarity, IMO,
> 
> pairs = [(value, offset) for (offset, value) in enumerate(hist)]
> pairs.sort()
> indexes = [offset for (value, offset) in pairs]
> 
> In Python2.4 this is allowed
> 
>  >>> hist = [ 0, 1, 0, 5, 43 ]
>  >>> [pair[0] for pair in sorted(enumerate(hist),
> ...                             key=lambda pair: pair[1])]
> [0, 2, 1, 3, 4]
>  >>>

   Even faster, though perhaps not as clear:

     >>> import operator
     >>> hist = [ 0, 1, 0, 5, 43 ]
     >>> map(operator.itemgetter(0), sorted(enumerate(hist),
     ...                             key=operator.itemgetter(1)))
     [0, 2, 1, 3, 4]

   Jp



More information about the Python-list mailing list