[Tutor] Sorting by numbers
Kent Johnson
kent37 at tds.net
Sun Aug 21 15:49:51 CEST 2005
Jonas Melian wrote:
> :( I get
> >>> modes
> [['85', '640x480'], ['85', '800x600'], ['85', '1024x768'], ['85',
> '1280x1024'], ['70', '1600x1200'], ['60', '1920x1440']]
> please help!
>
>
>>Solution:
>>modes.sort(key=lambda item: int(item[1].split('x')[0])) # 2.4
>>modes.sort(lambda x, y: cmp(int(x[1].split('x')[0]),
>>int(y[1].split('x')[0]))) #2.3.5
OK, you want to sort first by frequency, then by size, in descending order. So your key should include both frequency and size and you should include the reverse=True argument to sort. How about
modes.sort(key=lambda item: (int(item[0], int(item[1].split('x')[0])), reverse=True)
?
>>>From an input as this:
>>
>>>Standard timing 0: 85 Hz, 640x480
>>>Standard timing 1: 85 Hz, 800x600
>>>Standard timing 2: 85 Hz, 1024x768
>>>Standard timing 3: 85 Hz, 1280x1024
>>>Standard timing 4: 70 Hz, 1600x1200
>>>Standard timing 5: 60 Hz, 1920x1440
>>>
>>>I want to get columns 3 and 5 for sort them from mayor mo minor, so:
>>>
>>>85 1280x1024
>>>85 1024x768
>>>85 800x600
>>>85 640x480
>>>70 1600x1200
>>>60 1920x1440
>>>
>>>------
>>>modes = []
>>>i = 3; j = 5 # Columns for get
>>>for ln in data:
>>> if ln.startswith('Standard'):
>>> modes.append(ln.split()[i:j+1:j+1-i-1])
Alternately you could just build the list in the format you need it for correct sorting. This might be a bit more readable:
modes = []
for ln in data:
if ln.startswith('Standard'):
_, _, _, freq, _, dim = ln.split()
dim = map(int, dim.split('x'))
modes.append( (freq, dim) )
modes.sort(reverse=True)
for freq, dim in modes:
print '%s %dx%d' % (freq, dim[0], dim[1])
Kent
PS to Liam: I suppose you could think of the above as a Schwartzian Transform :-)
More information about the Tutor
mailing list