This code snippet shows you how to sort more complicated objects like a list of lists (or tuples) by selecting an index of the item to sort by.
Sorting complicated objects (Python)
# sorting a list of lists/tuples by index
# tested with Python 2.5.4 and Python 3.1.1 by vegaseat
import operator
# in [[name1, score1], [name2, score2], ...] score is at index=1
score = operator.itemgetter(1)
player_score = [['zoro', 88], ['jerry', 68], ['albert', 99]]
# sort by decreasing score
player_score.sort(key=score, reverse=True)
print(player_score)
"""my result -->
[['albert', 99], ['zoro', 88], ['jerry', 68]]
"""
print('-'*50)
# sort a more complicated combination of lists/tuples:
mylist = [
(1, ['a', '3.1', 'ad']),
(2, ['b', '4.0', 'bd']),
(3, ['c', '2.5', 'cd']),
]
# sort by item at index [1][1] of each tuple in mylist
# using a helper function like lambda
newlist = sorted(mylist, key=lambda tup: tup[1][1])
print(newlist)
"""my result (made pretty) -->
[
(3, ['c', '2.5', 'cd']),
(1, ['a', '3.1', 'ad']),
(2, ['b', '4.0', 'bd'])
]
"""
print('-'*50)
# or ...
# sort by item at index [1][1] of each tuple in mylist
# use the Schwartzian transform algorithm
# temporarily put a copy of indexed item in front
templist = [(x[1][1], x) for x in mylist]
templist.sort()
# remove temporary front item after sorting
newlist = [val for (temp, val) in templist]
print(newlist)
"""my result (made pretty) -->
[
(3, ['c', '2.5', 'cd']),
(1, ['a', '3.1', 'ad']),
(2, ['b', '4.0', 'bd'])
]
"""
Ene Uran 638 Posting Virtuoso
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.