Home > Backend Development > Python Tutorial > Analysis of the comparison principle of Python's built-in comparison function cmp

Analysis of the comparison principle of Python's built-in comparison function cmp

高洛峰
Release: 2016-10-18 09:33:45
Original
1420 people have browsed it

Analysis of the comparison principle of Pythons built-in comparison function cmp

cmp(x, y): Compares two objects. If the former is less than the latter, it returns -1, if they are equal, it returns 0, and if it is greater than the latter, it returns 1.

Python's cmp comparison function comparison principle

Python's cmp function You can compare between the same type or between different data types. Then determine the comparison size based on the return value of Python's cmp comparison function.

>>> 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
Copy after login

Observing several comparisons of the cmp function above, we can summarize:

Python's cmp comparison function, if we are comparing two similar objects, the comparison operation is very intuitive.

Comparison of numbers and strings, directly compare their values.

For comparison of sequence types, the methods are similar. Python tries to produce fair results when two objects are basically incomparable. For example, when two objects have no relationship, or when the two types have no functions for comparison at all, Python can only make conclusions based on "logic". Algorithm logic of comparison:

1. Compare the elements of the two lists.

2. If the compared elements are of the same type, compare their values ​​and return the result.

3. If the two elements are not of the same type type, check whether they are numbers.

a. If they are numbers, perform the necessary numeric cast, and then compare.

b. If the elements of one side are numbers, the elements of the other side are "big" (numbers) is "smallest")

c. Otherwise, compare by alphabetical order of type names.

4. If one list reaches the end first, then the other, longer list is "bigger".

5. If we If the elements of both lists are exhausted and all elements are equal, then the result is a tie, which means returning a 0.

This is the comparison principle of Python's cmp function

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template