sorting the list by inner elements
andrew-pythonlist at puzzling.org
Thu Mar 25 15:27:02 CET 2004
On Thu, Mar 25, 2004 at 07:31:16AM -0600, John Hunter wrote:
> >>>>> "ketulp" == ketulp baroda <ketulp_baroda at yahoo.com> writes:
> ketulp> I like ur idea but this will work for only when inner list
> ketulp> has only two elements. if inner list has five elements and
> ketulp> i want to sort the whole list by 3rd element then how can
> ketulp> i do this ?
> The general approach is to arrange the elements in the order you want
> them sorted, sort them, and then revert to original order. So if you
> have 5 elements, and you want them sorted by the 3rd, put the 3rd
> first. If any two of the first elements are the same, the second
> element of the list will break the tie, and so on.
> Supposing you want to sort by the 3rd element, and you don't care
> about the relative order of the other fields
> # swap the first an 3rd elements
> tmp = [ (e, e, e, e, e) for e in seq]
> # swap them back
> seq = [ (e, e, e, e, e) for e in tmp]
That's more complicated than it needs to be for ketulp's use-case.
tmp = [(e, e) for e in seq]
seq = [t for t in seq]
More information about the Python-list