Re: Sorting a multidimensional array by multiple keys
- From: Steven Bethard <steven.bethard@xxxxxxxxx>
- Date: Sat, 31 Mar 2007 09:40:02 -0600
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
.
- References:
- Sorting a multidimensional array by multiple keys
- From: Rehceb Rotkiv
- Re: Sorting a multidimensional array by multiple keys
- From: bearophileHUGS
- Re: Sorting a multidimensional array by multiple keys
- From: Rehceb Rotkiv
- Sorting a multidimensional array by multiple keys
- Prev by Date: Re: Is any way to split zip archive to sections?
- Next by Date: Re: Sorting a multidimensional array by multiple keys
- Previous by thread: Re: Sorting a multidimensional array by multiple keys
- Next by thread: Re: Sorting a multidimensional array by multiple keys
- Index(es):
Relevant Pages
|