An instance method for comparing two lists in python

  • 2021-07-09 08:49:14
  • OfStack

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

cmp () method syntax:


cmp(list1, list2)

Parameters:

list1--List of comparisons. list2--A list of comparisons.

Return value:

If the compared elements are of the same type, their values are compared and the result is returned.

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

If it is a number, perform the necessary number casting and compare. If the element on one side is a number, the element on the other side is "large" (the number is "minimum"). Otherwise, the comparison is made by alphabetical order of type names.

If one list reaches the end first, the other list that is 1 point longer is "big".

If we use up the elements of both lists and all the elements are equal, then the result is a draw, that is to say, 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 cmp methods:

Available methods are:

Expression subtraction (-) method:


print((a>b)-(a<b)) # 0, indicating that two lists are equal 

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 , Less than <

print(operator.gt(a,b)) #=> False , Greater than >

print(operator.eq(a,c)) #=> True , Equal to ==

print(operator.ne(b,a)) #=> True , Not equal to !=

print(operator.le(a,b)) #=> True , Less than or equal to <=

print(operator.ge(b,a)) #=> True , Greater than or equal to >=

Extended learning:

Two lists, randomly produce 4 unequal numbers, calculate 1, equal number of elements in the same position, represented by k1.

The elements in the b list are in the a list, but in different positions. How many are there, represented by k2.

For example:

a=[0, 4, 7, 3]
b=[7, 1, 0, 3]

k1=1 (only the fourth element is equal, k1=1)
k2 = 2 (0 and 7 in both lists, but in different positions, k2 = 2)


a=[]
b=[]
while(len(a)!=4):
  x=randint(0,9)
  if x not in a:
    a.append(x)
    
while(len(b)!=4):
  x=randint(0,9)
  if x not in b:
    b.append(x)
    
print(a)
print(b)
print()
k1=k2=0
for i in range(4):
  if a[i]==b[i]:
    k1+=1
  if b[i] in a and b[i]!=a[i]:
    k2+=1
    
print('k1=',k1)
print('k2=',k2)


Related articles: