Reputation: 439
For example, in python you have a list like this:
test = [[0, 'cde', 'efg'], [0, 'ac', 'dfg'], [0, 'ab', 'dfg'], [0, 'efg', 'cde']]
And you want to sort the 2nd and 3rd elements (i.e. index 1 and 2) in this list in alphabetical order, i.e. the new list:
test = [[0, 'cde', 'efg'], [0, 'ab', 'dfg'], [0, 'ac', 'dfg'], [0, 'efg', 'cde']]
How might one go about achieving this?
Upvotes: 0
Views: 63
Reputation: 52
You can achieve it like this :
res = test[:1] + sorted(test[1:3]) + test[3:]
Upvotes: 2
Reputation: 180401
test = [[0, 'cde', 'efg'], [0, 'ac', 'dfg'], [0, 'ab', 'dfg'], [0, 'efg', 'cde']]
sorted(test, key = lambda x: x[1:])
In [109]: test = [[0, 'cde', 'efg'], [0, 'ac', 'dfg'], [0, 'ab', 'dfg'], [0, 'efg', 'cde']]
In [110]: sorted(test,key=lambda x: x[1:])
Out[110]: [[0, 'ab', 'dfg'], [0, 'ac', 'dfg'], [0, 'cde', 'efg'], [0, 'efg', 'cde']]
You can use test.sort(key = lambda x: x[1:])
to sort the list in place an avoid creating a new list if that is preferable.
Upvotes: 0
Reputation: 31484
If you want to sort according to 2nd and 3rd elements use operator.itemgetter
:
from operator import itemgetter
test = [[0, 'cde', 'efg'], [0, 'ac', 'dfg'], [0, 'ab', 'dfg'], [0, 'efg', 'cde']]
print sorted(test, key=itemgetter(1,2))
Output
[[0, 'ab', 'dfg'], [0, 'ac', 'dfg'], [0, 'cde', 'efg'], [0, 'efg', 'cde']]
Upvotes: 0