Home > Backend Development > Python Tutorial > How to compare two lists in python

How to compare two lists in python

Release: 2019-07-03 16:50:22
Original
10078 people have browsed it

How to compare two lists in python

cmp() method is used to compare the elements of two lists.

cmp() method syntax:

cmp(list1, list2)
Copy after login

Parameters:

list1 -- The list to compare. list2 – the list to compare.

Return value:

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

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

If it is a number, perform the necessary number cast and then compare. If the element of one side is a number, then the element of the other side is "bigger" (the number is "smallest"). Otherwise, the comparison is done in alphabetical order of the type names.

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

If we exhaust the elements of both lists and all elements are equal, then the result is a tie, that is, a 0 is returned.

The following example shows how to use the cmp() function:

#!/usr/bin/python
list1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2);
print cmp(list2, list1);
list3 = list2 + [786];
print cmp(list2, list3)
Copy after login

Python3 no longer supports the cmp method:

The available methods are:

Expression subtraction (-) method:

print((a>b)-(a<b)) #0,表示俩list相等
Copy after login

operator module comparison operation:

import  operator
 
a=[1, 2, 3, 4, 5 ]
b=[1, 2, 3, 4, 5,6 ]
c=[1, 2, 3, 4, 5 ]
print(operator.lt(a,b)) #=> True ,小于<
print(operator.gt(a,b)) #=> False ,大于>
print(operator.eq(a,c)) #=> True ,等于==
print(operator.ne(b,a)) #=> True ,不等于!=
print(operator.le(a,b)) #=> True ,小于等于<=
print(operator.ge(b,a)) #=> True ,大于等于>=
Copy after login

For more Python related technical articles, please visit Python tutorial Column for learning!

The above is the detailed content of How to compare two lists in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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