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 »

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...