This question already has an answer here:
这个问题在这里已有答案:
- Why does “return list.sort()” return None, not the list? 6 answers
- What is the difference between `sorted(list)` vs `list.sort()`? 6 answers
为什么“return list.sort()”返回None,而不是列表? 6个答案
`sorted(list)`vs`list.sort()`有什么区别? 6个答案
I am trying to sort a list of objects in python, however this code will not work:
我试图在python中对对象列表进行排序,但是这段代码不起作用:
import datetime
class Day:
def __init__(self, date, text):
self.date = date
self.text = text
def __cmp__(self, other):
return cmp(self.date, other.date)
mylist = [Day(datetime.date(2009, 01, 02), "Jan 2"), Day(datetime.date(2009, 01, 01), "Jan 1")]
print mylist
print mylist.sort()
The output of this is:
这个输出是:
[<__main__.Day instance at 0x519e0>, <__main__.Day instance at 0x51a08>]
None
Could somebody show me a good way solve this? Why is the sort()
function returning None
?
有人能告诉我解决这个问题的好方法吗?为什么sort()函数返回None?
2 个解决方案
#1
mylist.sort() returns nothing, it sorts the list in place. Change it to
mylist.sort()不返回任何内容,它会对列表进行排序。将其更改为
mylist.sort()
print mylist
to see the correct result.
看到正确的结果。
See http://docs.python.org/library/stdtypes.html#mutable-sequence-types note 7.
请参阅http://docs.python.org/library/stdtypes.html#mutable-sequence-types注7。
The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.
sort()和reverse()方法在排序或反转大型列表时修改列表以便节省空间。为了提醒您它们是由副作用操作的,它们不会返回已排序或反转的列表。
#2
See sorted
for a function that will return a sorted copy of any iterable.
请参阅排序函数,该函数将返回任何iterable的排序副本。
#1
mylist.sort() returns nothing, it sorts the list in place. Change it to
mylist.sort()不返回任何内容,它会对列表进行排序。将其更改为
mylist.sort()
print mylist
to see the correct result.
看到正确的结果。
See http://docs.python.org/library/stdtypes.html#mutable-sequence-types note 7.
请参阅http://docs.python.org/library/stdtypes.html#mutable-sequence-types注7。
The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.
sort()和reverse()方法在排序或反转大型列表时修改列表以便节省空间。为了提醒您它们是由副作用操作的,它们不会返回已排序或反转的列表。
#2
See sorted
for a function that will return a sorted copy of any iterable.
请参阅排序函数,该函数将返回任何iterable的排序副本。