使用 python 我需要處理以下場景,其中我們有兩個串列 name_1 是靜態的,而 name_2 是動態的。當我們比較兩個串列時,如果 name_2 中有任何缺失或部分值,那么我需要列印與 name_2 對應的 name_1 值。
2 場景:如果 name_2 中有額外的值,那么我需要直接列印它。
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
預期輸出 1:
Incorrect element founded in position python_code
預期輸出 2:
'mari' is extra column in position 4
uj5u.com熱心網友回復:
您可以使用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)
這列印:
Incorrect element 'python_code' founded in position 2
'mari' is extra column in position 4
#list_match = [0, 1, 3]
uj5u.com熱心網友回復:
快速回答:
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}")
然后只需將其反轉為另一個串列。
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}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/382211.html
