在Python中对对象集合排序
在我现在做的Twitter克隆项目中,我正在学习Python和Django。我有一组对象,叫做Tweets(推文),我想按照它们的发布时间(pub_date)来排序。发布时间是指它们被发布的具体时间。因为集合(set)没有排序的方法(也没有像QuerySets那样方便的order_by),那么有什么好的办法可以对这个集合进行排序呢?
谢谢!
3 个回答
0
你需要把那个集合转换成一个列表。可以用这行代码:your_list = list(your_set)
#To sort the list in place... by "pub_date"
your_list.sort(key=lambda x: x.pub_date, reverse=True)
#To return a new list, use the sorted() built-in function...
newlist = sorted(your_list, key=lambda x: x.pub_date, reverse=True)
0
你可以把你的集合传给 sorted
函数,这个函数会返回一个排好序的列表。sorted
函数可以接收一个“关键字”,你可以给它提供一个自定义的函数来对你的项目进行排序:
>>> s = set('abcde')
>>> s
set(['a', 'c', 'b', 'e', 'd'])
>>> sorted(s, key = lambda x: -ord(x))
['e', 'd', 'c', 'b', 'a']