Sort

sorted() vs. sort()

  • sort() makes change in place which return NONE, while sorted() will make copy of sorted list, which keep original list

  • sorted() can work for any iterable, not only list, strings, tuple, dictionaries

  • speed:

    • for list, sort() faster than sorted() since there is no process for making copy
    • for other iterable, only sorted()
  • for sort(), it can not retrieve back to orignial place since it has been changed

sorting string containing number

What should we do when sorting list such like a = [‘s-2’,’s-6’,’s-19’,’s-15’,’s-20’]?

>>> sorted(a)
# ['s-15', 's-19', 's-2', 's-20', 's-6']

Well, it is not in order by number. When sorting string, it compares first letter, then compare one by one, not as whole number.
-> sorted(iterable, key(optional), reverse(optional))

>>> sorted(a, key=lambda x: x.split('-')[:-1])
# ['s-2', 's-6', 's-19', 's-15', 's-20']
# sort

Commentaires

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×