Python | sorted() And list.sort(

2018-05-17  本文已影响49人  Ghibli_Someday

They are both built-in functions, the difference is:

sort()

Eg:

>>> a = [5,2,4,3,1]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]

PS:It is just suitable for list!

sorted(iterable[,key][,reverse])

The default values of key and reverse are respectively None and False.

Eg:

students = {
    ('join','A',15),
    ('jane','B',12),
    ('dave','B',10),
}
# sorted by age
s = sorted(students, key=lambda student:student[2])
print(s)
>>>
[('dave', 'B', 10), ('jane', 'B', 12), ('join', 'A', 15)]

With reverse:

students = {
    ('join','A',15),
    ('jane','B',12),
    ('dave','B',10),
}
# sorted by age
s = sorted(students, key=lambda student:student[2], reverse=True)
print(s)
>>>
[('join', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

BTW:

As a mutable object, list has a method : list.reverse()

The method modifies the sequence in place for economy of space of when reversing a large sequence
Attention:To remind users that operates by side effect, it does not return the reversed sequence

>>> L = [5, 2, 9, 0]
>>> L.reverse()
>>> L
[0, 9, 2, 5]

or

>>> L = [5, 2, 9, 0]
>>> reversed(L)
<list_reverseiterator object at 0x00000202638F7358>
>>> L
[5, 2, 9, 0]
>>> list(reversed(L))
[0, 9, 2, 5]

Pls notice the difference of results of list.reverse() and reversed()

---------------Referred By Library References---------------

上一篇 下一篇

猜你喜欢

热点阅读