Python sorting - A list of objects
Of course, it doesn't have to be a lambda. Any function passed in, such as the below one, will work
def numeric_compare(x, y):
if x > y:
return 1
elif x == y:
return 0
else: #x < y
return -1
a = [5, 2, 3, 1, 4]
a.sort(numeric_compare)
Source : Python Sorting
So, in your case ...
def object_compare(x, y):
if x.resultType > y.resultType:
return 1
elif x.resultType == y.resultType:
return 0
else: #x.resultType < y.resultType
return -1
a.sort(object_compare)
The aforementioned lambda is definitely the most compact way of doing it, but there's also using operator.itemgetter.
import operator
#L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
map(operator.itemgetter(0), L)
#['c', 'd', 'a', 'b']
map(operator.itemgetter(1), L)
#[2, 1, 4, 3]
sorted(L, key=operator.itemgetter(1))
#[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
So you'd use itemgetter('resultType'). (Assuming getitem is defined.)
sorted(L, key=operator.itemgetter('resultType'))
somelist.sort(key = lambda x: x.resultType)
Here's another way to do the same thing that you will often see used:
import operator
s.sort(key = operator.attrgetter('resultType'))
You might also want to look at sorted
if you haven't seen it already. It doesn't modify the original list - it returns a new sorted list.