[Tutor] Sorting lists both ways at once and programmatically loading a variable.
Alan Gauld
alan.gauld at btinternet.com
Fri Jul 29 01:53:32 CEST 2011
Prasad, Ramit wrote:
> I have 2 questions.
>
> 1. Is there a way to do a reverse and a normal sort at the same time?
> I have a list of tuples (there are more than 2 elements in the tuples but I only want to sort by the first two). I want to sort in reverse for the first element (int) and in order for the second element (string).
>
> Example: [ (1,3) (5, 2), (5, 1), (1, 1) ].
> The output should be:[ (5,1), (5,2), (1,1), (1,3) ]
> I can create a hack for this by sorting both values in order but it is a hack and not a "Good" solution (untested):
>>>> sorted( lst, key=lambda x: (9999999999-x[0],x[1]) )
Its late and I'm going to bed so this might be ruibbish, but couldn't
you just negate the first element? So -5 is smaller than -1 etc...
> 2. How would you programmatically get a variable when there is no class involved? If I was in a class I could do something like
>>>> programmatically_determined_variable = getattr( self, var_basename + str(number) )
> How would I do this from a module function or directly in the module? And is the solution "safe"?
Sorry, brain hurts trying to work out what you mean here... :-)
Good night,
Alan G.,
More information about the Tutor
mailing list