对于我目前的Twitter Clone项目,我正在学习Python/Django,我现在有一组对象,Tweets,我想按pub_date排序,当然这是它们发布的日期时间。既然集合没有排序方法(或者QuerySets提供的方便的order_by ),那么对这个集合进行排序的最好方法是什么?
谢谢
发布于 2014-03-15 01:29:15
发布于 2014-03-15 01:38:07
您需要将该集合转换为列表。使用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)发布于 2014-03-15 01:42:35
你可以将你的set传递给sorted函数,它将返回一个排序的列表,排序的函数将接受一个键,你可以为它提供一个自定义的函数来对你的项目进行排序:
>>> s = set('abcde')
>>> s
set(['a', 'c', 'b', 'e', 'd'])
>>> sorted(s, key = lambda x: -ord(x))
['e', 'd', 'c', 'b', 'a']https://stackoverflow.com/questions/22411823
复制相似问题