Bullet Option:
- Sort (*, key=none, reverse=none)
The sort method is used for in-place sorting, can receive two keyword-only parameters, and the sort of this method is stable.
Key: An expression that, when compared, sorts based on the result of the expression's calculation
Reverse: Default false, ascending order; True, descending order
Use ascending order By default
>>> source=[5,2,8,4,3,6,7]>>> source.sort ()print(source) [2, 3, 4, 5, 6, 7, 8]
Reverse=true, using descending order
>>> source=[5,2,8,4,3,6,7]>>> source.sort (reverse=True)print( SOURCE) [8, 7, 6, 5, 4, 3, 2]
Key is used to enter a method for calculating weights, and sorting is sorted by weight rather than by original value
def cal_priority (target): return 0-target>>> source=[5,2,8,4,3,6,7] for in source] Print(result) [-5,-2,-8, -4, -3,-6,-7]>>> source.sort (key=Cal_ Priority)print(source) [8, 7, 6, 5, 4, 3, 2]
- Sorted (iterable[, key][, reverse])
The sorted () method is similar to the sort () method, but the former returns a new list with no effect on the original list.
List derivation is a very interesting feature that has been used in the previous sort () method, and concise syntax can save a lot of code in use.
def cal_priority (target): return 0-target>>> source=[5,2,8,4,3,6,7]result=[cal_priority (item) for Item in source]print(result) [-5,-2,-8,-4,-3,-6,-7]
The grammatical structure also provides a clear understanding of how it is done, and the overall reading direction is from right to left:
The preferred pair of "[]" means that this returns a list with "for item in source" stating that a target list needs to be cycled, "cal_priority" to indicate how each data in the loop is to be computed.
Sharding is also an effective way to save code, simple ":" can easily filter out the list of specified parts, and even easy to copy the list
LIST[M:N] Represents a list item that returns the first m position of the list to the nth position, but does not include the first m position, and if M, n is empty, the copy of the original list is returned
>>> source=[1,2,3,4,5,6]print(source[2:5]) [3, 4, 5]>>> result=source[:]print(result) [1, 2, 3, 4, 5, 6]>>> result=[] Print (source) [1, 2, 3, 4, 5, 6]
Read the document to find out, in fact, this is a class, rather than a method Otz. One application scenario for a collection class is to go heavy and the effect is immediate.
In addition to the weight of this, the collection itself is a very interesting data structure, but to achieve a lot of interesting features.
Python also has a type called class frozenset([iterable]) . The collection type, as the name implies, Frozenset is frozen, cannot modify the data therein.
>>> source=[5,5,7,2,8,4,3,4,6,7]>>> sourceset=Set (source)print( Sourceset) {2, 3, 4, 5, 6, 7, 8}
Why the output is sorted, repeated a lot of times are like this???
Head Frist Python Reading notes Chapter fifth processing data