Home >Backend Development >Python Tutorial >How to compare two lists in python
cmp() method is used to compare the elements of two lists.
cmp() method syntax:
cmp(list1, list2)
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)
Python3 no longer supports the cmp method:
The available methods are:
Expression subtraction (-) method:
print((a>b)-(a<b)) #0,表示俩list相等
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 ,大于等于>=
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!