Sorting a multidimensional array by multiple keys

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Sat Mar 31 18:14:13 CEST 2007


On Mar 31, 6:42 am, Rehceb Rotkiv <reh... at no.spam.plz> wrote:

(snipped)

> As each line consists of 5 words, I would break up the data into an array
> of five-field-arrays (Would you use lists or tuples or a combination in
> Python?). The word "BUT" would be in the middle, with two fields/words
> left and two fields/words right of it. I then want to sort this list by
>
> - field 3
> - field 4
> - field 1
> - field 0



import StringIO

buf = """
reaction is BUT by the
sodium , BUT it is
sea , BUT it is
this manner BUT the dissolved
pattern , BUT it is
rapid , BUT it is
""".lstrip()

mockfile = StringIO.StringIO(buf)

tokens = [ line.split() + [ line ] for line in mockfile ]
tokens.sort(key=lambda l: (l[3], l[4], l[1], l[0]))
for l in tokens:
    print l[-1],


--
Hope this helps,
Steven




More information about the Python-list mailing list