(Excerpt from rookie Tutorial: https: //www.runoob.com/python/python-func-sorted.html):
sorted () function is a built-in function of python may effect ** ** sort operation on all the objects iterations.
1.sort and sorted differences:
sorted can be sorted objects operate all iterations, the return value, to return a list ;
sort is a method used in the list , sort method of the list is a list of already present inplace operation, no return value .
2.sorted syntax:
sorted(iterable, cmp=None, key=None, reverse=False)
3.sorted Parameter Description:
Iterable - iterables.
cmp - compare function, the two parameters, parameter values are taken from the subject may be iterative, this function must comply with the rules is greater than 1 is returned, it is less than -1, is equal to 0 is returned.
key - is mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to be sorted.
reverse - collation, reverse = True descending, reverse = False ascending (default).
return:
return the list to reorder ** **.
4. sort syntax:
list.sort(cmp=None, key=None, reverse=False)
cmp - optional parameter, if this parameter is a method of using the parameter designated for sorting.
key - is mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to be sorted.
reverse - collation, Reverse descending = True, Reverse ascending = False (default).
example:
x=[3,1,2,56,7,90,22] y="AlexSun" z=zip(x,y) print(sorted(x)) print(sorted(y)) print(sorted(z))
print("Unsorted x is:")
print(x)
print("The sorted x is:")
x.sort()
print(x)
operation result:
[1, 2, 3, 7, 22, 56, 90] ['A', 'S', 'e', 'l', 'n', 'u', 'x'] [(1, 'l'), (2, 'e'), (3, 'A'), (7, 'S'), (22, 'n'), (56, 'x'), (90, 'u')] Unsorted x is: [3, 1, 2, 56, 7, 90, 22] The sorted x is: [1, 2, 3, 7, 22, 56, 90]