Using python I would need to tackle the below scenario, where we have two lists name_1 is static and name_2 is dynamic. When we compare the two lists if there is any missing or partial value in name_2 then i need to print the name_1 value corresponding to name_2.
2 scenario: If there is extra value in name_2 then i need to print it directly.
name_1 = ['mahesh','karthik','python_code','Karun']
name_2 = ['mahesh','karthik','pyth','Karun','mari']
list_match = []
i = 0
while i < len(name_2):
if not name_2[i]:
print("Incorrect element founded in position ", name_1[i])
break
elif name_2[i] not in name_1:
print(f"'{name_2[i]}' is extra column in position ", i)
break
else:
list_match.append(i)
i =1
Expected Output1:
Incorrect element founded in position python_code
Expected Output2:
'mari' is extra column in position 4
CodePudding user response:
You can use itertools.zip_longest
:
from itertools import zip_longest
name_1 = ['mahesh','karthik','python_code','Karun']
name_2 = ['mahesh','karthik','pyth','Karun','mari']
list_match = []
for idx, (i, j) in enumerate(zip_longest(name_1, name_2)):
if i is None:
print("'{}' is extra column in position {}".format(j, idx))
elif i!=j:
print("Incorrect element '{}' found in position {}".format(i, idx))
else:
list_match.append(idx)
This prints:
Incorrect element 'python_code' founded in position 2
'mari' is extra column in position 4
#list_match = [0, 1, 3]
CodePudding user response:
Quick answer:
mismatches = [(i, el) for i, el in enumerate(name_1) if not el in name_2]
for idx, el in mismatches:
print(f"Incorrect element founded in position {idx}: {el}")
Then just reverse it for the other list.
mismatches = [(i, el) for i, el in enumerate(name_2) if not el in name_1]
for idx, el in mismatches:
print(f"Incorrect element founded in position {idx}: {el}")