Comparing Same Index In 2 Lists
Solution 1:
zip
the lists and return the test (which returns a boolean as outcome):
[i == j for i, j in zip(x_list, y_list)]
You could use any
to quickly check for the existence of a False
(means the items are not the same) if you don't need the values:
any(i != j for i, j in zip(x_list, y_list))
The any
version would break once a False
is found meaning you may not have to traverse the whole lists except in the worst case.
Solution 2:
You can always use list comprehensions:
[True if i == j else False for i,j in zip(x_list, y_list)]
.
You can also check less explicit answer by Moses Koledoye, where True if i == j else False
is juzt i == j
zip function will combine your lists like [(1, 1), (2, 2), (3, 'A'), (4, 'B'), (5, 5)]
Result: [True, True, False, False, True]
Also suggest to use izip from itertools if you use Python2.
Solution 3:
try this:
[i == j for i, j in zip(x_list, y_list)]
Solution 4:
You can try with below definition if you would like to compare lists with different size. This would fetch either unique index elements or not rather than a list of True or False.
def is_uniq_lists(x_list, y_list):
if len(x_list) != len(y_list):
return False
for (i,j) in zip(x_list, y_list):
if i != j: return False
return True
Result:
>>> a = [1,2,3,4,5] # Unique lists
>>> b = [1,2,3,4,5]
>>> List.is_uniq_lists(a,b)
True
>>> a=[1,2,3,4,5] # Different lists
>>> b=[1,2,'A','B',5]
>>> List.is_uniq_lists(a,b)
False
>>> a=[1,2,3,4,5]
>>> b=[1,2,3,4,5,6] # Lists of unequal length
>>> List.is_uniq_lists(a,b)
False
Solution 5:
def compareArrayIndex(L1, L2):
if(len(L1) == len(L2)):
for i in range(0, len(L2)):
if(L1[i] > L2[i]):
# logic
elif(L1[i] < L2[i]):
# logic
else:
# logic
return value
Post a Comment for "Comparing Same Index In 2 Lists"