I'd like to use the somelist.sort() method to do this if possible.
I have a list containing objects, all objects have a member variable resultType that is an integer. I'd like to sort the list using this number.
How do I do this?
Thanks!
Python lists have a built-in list. sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.
sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.
A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.
Filter a Python List with filter() The filter(function, iterable) function takes a function as input that takes on argument (a list element) and returns a Boolean value whether this list element should pass the filter. All elements that pass the filter are returned as a new iterable object (a filter object).
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.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With