Hayley van Waas
Hayley van Waas

Reputation: 439

Sorting an element according to contents of sublist?

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

Answers (3)

Cedar
Cedar

Reputation: 52

You can achieve it like this :

res = test[:1] + sorted(test[1:3]) + test[3:]

Upvotes: 2

Padraic Cunningham
Padraic Cunningham

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

enrico.bacis
enrico.bacis

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

Related Questions