在Python中对一组对象进行排序

时间:2014-03-14 17:25:46

标签: python django sorting

对于我目前正在学习Python / Django的Twitter Clone项目,我目前有一组对象,Tweets,我想按pub_date排序,这当然是它们发布时的日期时间。由于集合没有排序方法(或者QuerySets具有的方便顺序),对这个集合进行排序的最佳方法是什么?

谢谢

3 个答案:

答案 0 :(得分:0)

您可以通过标准sorted函数从list生成set个已排序元素,并使用自定义key仿函数访问要排序的正确元素。但是你无法对set中的实际元素进行排序,因为python中的set根据定义是无序的。

set文档的标题字面上是'无序的独特元素集合' 。这与set不支持索引访问的原因相同,因为set的顺序随每个元素插入而变化。

答案 1 :(得分: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)

答案 2 :(得分:0)

您可以将您的设置传递给sorted功能,该功能将返回已排序的列表,已排序的功能将获取一个键,您可以为其提供自定义功能以对您的项目进行排序:

>>> s = set('abcde')
>>> s
set(['a', 'c', 'b', 'e', 'd'])
>>> sorted(s, key = lambda x: -ord(x))
['e', 'd', 'c', 'b', 'a']
相关问题