Re: Sorting a multidimensional array by multiple keys



On Mar 31, 6:42 am, Rehceb Rotkiv <reh...@xxxxxxxxxxx> 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

.



Relevant Pages

  • Re: why cannot assign to function call
    ... I'm going to follow up here at the risk of annoying Mark, ... helpful in explaining things to Python beginners. ... it becomes a namespace mapping names to objects. ... to the list itself, while Steven held that Python lists ...
    (comp.lang.python)
  • python-dev Summary for 2003-10-16 through 2003-11-15
    ... This is the twenty-eighth and twenty-ninth summaries written by Brett ... The in-development version of the documentation for Python can be found ... If you have ever wanted to see linked lists used in Python in a rather ... Contributing threads: ...
    (comp.lang.python)
  • TOC of Python Cookbook now online (was Re: author index for Python Cookbook 2?)
    ... Processing a String One Character at a Time ... Finding a File on the Python Search Path ... Constructing Lists with List Comprehensions ... Looping over Items and Their Indices in a Sequence ...
    (comp.lang.python)
  • chapter4
    ... The for statement in Python differs a bit from what you may be used to ... list or a string), in the order that they appear in the sequence. ... (this can only happen for mutable sequence types, such as lists). ... The keyword def introduces a function definition. ...
    (Ubuntu)
  • Re: c[:]()
    ... Python source, nor have I looked at the BNF, lately. ... Is there some other mitigating factor? ... The python3000 and python-ideas lists are the correct forum for those issues, though you will of course get all sorts of opinions on c.l.py. ...
    (comp.lang.python)