To sort the list in place:
orig_list.sort(key=lambda x: x.count, reverse=True)
To return a new list, use sorted:
new_list = sorted(orig_list, key=lambda x: x.count, reverse=True)
Explanation:
key=lambda x: x.countsorts by count.reverse=Truesorts in descending order.
More on sorting by keys.
Answer from Kenan Banks on Stack OverflowTo sort the list in place:
orig_list.sort(key=lambda x: x.count, reverse=True)
To return a new list, use sorted:
new_list = sorted(orig_list, key=lambda x: x.count, reverse=True)
Explanation:
key=lambda x: x.countsorts by count.reverse=Truesorts in descending order.
More on sorting by keys.
A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:
try: import operator
except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module
else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda
ut.sort(key=keyfun, reverse=True) # sort in-place
So I want to sort a list of objects by a particular attribute that they have using the "sorted" function because the timsort algorithm that the "sorted" function has is super fast.
a list like this, having objects which have a certain attribute "a" which is an int
object_list = [object1, object2, object3]
for i in object_list:
print(i.a)output:
30
56
23
how do I sort this list by that attribute in ascending order using the "sorted" function?
thanks in advance!
How to sort a list of objects?
Python - Sort list by object attribute [x-post via /r/learnpython]
Setting list as a class attribute
Unresolved attribute??
Maybe you used tile somewhere else in your code? The above works for me. But read pep8 for naming conventions, check out itertools.product and sets for some suggestions on making your code a little prettier.