Analysis of the cmp comparison principle of Python built-in comparison functions
Cmp (x, y): compares two objects. if the former is smaller than the latter,-1 is returned. if the former is equal, 0 is returned. if the former is greater than the latter, 1 is returned.
Comparison principle of cmp comparison functions in Python
The cmp functions of Python can be compared between the same type or between different data types. The comparison size is determined based on the return values of the cmp comparison function in Python.
>>> list1, list2 = [123, 'xyz'], [456, 'abc']>>> cmp(list1, list2)-1>>> cmp(list2, list1)1>>> list3 = list2 + [789]>>> list3[456, 'abc', 789]>>> cmp(list2, list3)-1
Observe the comparison of the above cmp functions and summarize the following:
The cmp comparison function of Python. if we compare two similar objects, the comparison operation is very intuitive.
Compare numbers with strings to directly compare their values.
For comparison of sequence types, the methods are similar. Python tries its best to make fair results when two objects cannot be compared. For example, if there is no relationship between two objects or there are no comparison functions for the two types, Python can only draw conclusions based on "logic. Comparison algorithm logic:
1. compare the two list elements.
2. if the comparison element is of the same type, compare its value and return the result.
3. if the two elements are not of the same type, check whether they are numbers.
A. If it is a number, perform the necessary mandatory numeric type conversion and then compare.
B. If one element is a number, the other element is "big" (the number is "smallest ")
C. Otherwise, the type names are compared in alphabetical order.
4. if a list first reaches the end, the other long list will be "large ".
5. if we use up two list elements and all elements are equal, the result is a draw.
0 is returned.
This is the comparison principle of the cmp functions in Python.