Re: Sorting a multidimensional array by multiple keys



Rehceb Rotkiv wrote:
If you want a good answer you have to give me/us more details, and an
example too.

OK, here is some example data:

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

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

You're probably looking for the key= argument to list.sort(). If your function simply returns the fields in the order above, I believe you get the right thing::

>>> s = '''\
.... 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
.... '''
>>> word_lists = [line.split() for line in s.splitlines()]
>>> def key(word_list):
.... return word_list[3], word_list[4], word_list[1], word_list[0]
....
>>> word_lists.sort(key=key)
>>> word_lists
[['reaction', 'is', 'BUT', 'by', 'the'],
['pattern', ',', 'BUT', 'it', 'is'],
['rapid', ',', 'BUT', 'it', 'is'],
['sea', ',', 'BUT', 'it', 'is'],
['sodium', ',', 'BUT', 'it', 'is'],
['this', 'manner', 'BUT', 'the', 'dissolved']]

STeVe
.



Relevant Pages