简体   繁体   中英

Can anyone explain why this sorting won't work?

For example if I have a list like this:

List1 =[7,6,9]
List1 = List1.sort()

list.sort() sorts the list in-place and returns None , so you were actually assigning that return value to List1 , ie None .

>>> List1 =[7,6,9]
>>> repr(List1.sort())
'None'                     #return Value of list.sort
>>> List1                  #though list is sorted
[6, 7, 9]

On the other hand the built-in function sorted returns a new sorted list:

>>> List1 =[7,6,9]
>>> sorted(List1)
[6, 7, 9]
>>> List1           #List1 is not affected
[7, 6, 9]

You can assign back the result of sorted to List1 , but this makes no sense as list.sort will do the same thing and in lesser time.

>>> List1 = sorted(List1)
>>> List1
[6, 7, 9]

Though the above code was similar to list.sort , but actually it's a bit different because it returns new list. Example:

>>> List1 =[7,6,9]
>>> List2 = List1         # both List1, List2 point to the same object [7, 6, 9]
>>> List1.sort()          # sort List1 in-place, affects the original object
>>> List1, List2
([6, 7, 9], [6, 7, 9])    # both variables still point to the same list

>>> List1 =[7,6,9]
>>> List2 = List1         #same as above
>>> List1 = sorted(List1) #sorted returns a new list, so List1 now points to this new list 
>>> List1, List2          #List2 is still unchanged
([6, 7, 9], [7, 6, 9])

Timing comparisons:

>>> from random import shuffle

>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit lis.sort()
1 loops, best of 3: 9.9 ms per loop

>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit sorted(lis)
1 loops, best of 3: 95.9 ms per loop

So, sorted should be used only when you don't want to affect the original list and want to assign the sorted version of that list to some other variable.

Apart from lists other data-structures like set , tuples , dicts ,etc don't have their own .sort() method, so sorted is the only thing you can use there.

>>> s = {1,5,3,6}  # set
>>> sorted(s)
[1, 3, 5, 6]

help on sorted :

>>> print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

.sort() sorts the list in place. It does not return the new list. Infact, as it doesn't return anything by default, it returns None .

If you want the sorted list returned, you can use sorted() :

List1 = sorted(List1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM