Today, in http://www.pythontip.com, I encountered a sort of problem: a list of both strings, and numbers, how to sort.
List = [1,2,5,4,'d','s','e', 45 ]list.sort ()
If you call the sort () function directly, you will be quoted
TypeError Traceback (most recent call last) in <module>()----> 1'< ' not'str'and'int'
I understand that the sort () function internally is a comparison of size by ' < ', and ' < ' does not support comparisons between strings and numbers.
Later we found a sorted () function to solve the sorting problem with strings and numbers
New_list = sorted (list)
Sorted () is not the same as sort (), sorted () is to sort the list as a parameter, and then get the sorted list, and sort () is sorted on the basis of the original list.
The sort () function is defined only in the list, and sorted () is valid for all iteration objects.
Use Help () to see the difference between the two:
---------------------------------Sorted----------------------------------------
in [+]: Help (List.sort)
Help on built-in function sort:
Sort (...) method of Builtins.list instance
L.sort (Key=none, Reverse=false), None--stable sort *in place*
--------------------------------Sorted---------------------------------------
In [All]: Help (sorted)
Help on built-in function sorted in module Builtins:
Sorted (iterable,/, *, Key=none, Reverse=false)
Return a new list containing all items from the iterable in ascending order.
A Custom key function can be supplied to customize the sort order, and the
Reverse flag can is set to request the result in descending order.
Ascending returns a new list that contains the iterations for all items.
You can provide a custom key function to customize the sort order, and you can set a reverse flag to return the results in descending order.
Sorting in Python