Sorting a multidimensional array by multiple keys
Duncan Booth
duncan.booth at invalid.invalid
Sat Mar 31 11:44:34 EDT 2007
Rehceb Rotkiv <rehceb at no.spam.plz> wrote:
> Wait, I made a mistake. The correct result would be
>
> 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
>
> because "by the" comes before and "the dissolved" after "it is". Sorry
> for the confusion.
>>> 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",
]
>>> data = [ s.split() for s in data]
>>> from pprint import pprint
>>> pprint(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']]
>>> from operator import itemgetter
>>> data.sort(key=itemgetter(0))
>>> data.sort(key=itemgetter(1))
>>> data.sort(key=itemgetter(4))
>>> data.sort(key=itemgetter(3))
>>> pprint(data)
[['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']]
More information about the Python-list
mailing list