Built-in function -sorted
To sort List and Dict, Python provides two methods.
Sorts the given List L.
Method 1, use the member function sort of List to sort, sort locally, and do not return a copy.
Method 2. Sort with the built-in function sorted (since 2.4), return a copy, the original input is unchanged.
--------------------------------sorted--------------------------------
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 customise the sort order, and the
reverse flag can be set to request the result in descending order.
-------------------------------------------------- --------------------
Parameter description: It is an iterable type.
key: pass in a function name, the parameter of the function is each item in the iterable type, sorted according to the size of the return value of the function.
reverse: collation, reverse=True descending or reverse=False ascending, with default values.
Return value: ordered list
Columns:
The list is sorted by the absolute value of each value
l1 = [1,3,5,-2,-4,-6]
l2 = sorted(l1,key=abs)
print(l1)
print(l2)
输出:
[1, 2, 3, -2, -4, -6]
[1, 2, -2, 3, -4, -6]
The list is sorted by the len of each tuple
l= [[1,2],[3,4,5,6],(7,),'123']
print(sorted(l,key=len))
output:
[(7,), [1, 2], '123', [3, 4, 5, 6]]