2017年10月2日 星期一

[ Python 常見問題 ] How to sort a list of objects , based on an attribute of the objects?

Source From Here 
Question 
I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like: 
>>> class Tag:
... def __init__(self, count):
... self.count = count
...
>>> alist = [Tag(1), Tag(3), Tag(4), Tag(2)]
>>> alist[0].count
1

Each object has a count. I need to sort the list by number of counts descending. 

How-To 
A few examples as below: 
# To return a new list, use the sorted() built-in function...
>>> nlist = sorted(alist, key=lambda x:x.count, reverse=True)
>>> for i in nlist:
... print("{}".format(i.count))
...
4
3
2
1


# To sort the list in place...
>>> alist.sort(key=lambda x:x.count, reverse=True)
>>> for i in alist:
... print("{}".format(i.count))
...
4
3
2
1

More on sorting by keys »

沒有留言:

張貼留言

[Linux 常見問題] How to set a file size limit for a directory?

Source From   Here   Question   I   have a directory on my system which is used for a specific reason by applications and users , but I   d...