匹配两个列表之间的元素,但索引索引

时间:2020-05-27 12:02:56

标签: python

让我们说我有这两个列表:

lst1 = ['A1','B1','C1']

lst2 = ['A1','B2']

对于lst1中的每个元素,将其与lst2中的对应元素进行比较 按索引(对于lst2中的所有元素,1-1不是1)。如果找到匹配项,则输出如下内容:'match found between A1 and A1 at index 0 in both lists'

如果元素与输出不匹配 应该这样:'Elements at index 1 do not match"

如果lst1的索引2处的元素在lst2的索引中没有对应的索引 :'For element at index 3, 'C1', no corresponding match found in lst3.

我尝试过的:

 for i in range(len(lst1)):

            if lst1[i] == lst2[i]:

                return 'Match between...'
            else:
                return 'Not matched...'

当列表长度不匹配时,它会失败,此外,我敢肯定有一种更聪明的方法可以做到这一点。

2 个答案:

答案 0 :(得分:0)

尝试一下:

lst1 = ['A1','B1','C1']
lst2 = ['A1','B2']

max_length = max(len(lst1), len(lst2))
for i in range(max_length):
    try:
        if lst1[i] == lst2[i]:
            print(f'match found between {lst1[i]} and {lst2[i]} at index {i} in both lists')
        else:
            print(f"Elements at index {i} do not match")

    except:
        if len(lst1) >= i:
            print(f"For element at index {i}, {lst1[i]}, no corresponding match found in lst2.")
        else:
            print(f"For element at index {i}, no corresponding match found in lst2. {lst2[i]}")

将产生以下输出:

match found between A1 and A1 at index 0 in both lists
Elements at index 1 do not match
For element at index 2, C1, no corresponding match found in lst2.

答案 1 :(得分:-1)

在这种情况下,我建议您使用itertools.zip_longest()

from itertools import zip_longest

lst1 = ["A1", "B1", "C1"]
lst2 = ["A1", "B2"]
ziplist = list(zip_longest(lst1, lst2))

for i in range(len(ziplist)):
    print(ziplist[i][0], ziplist[i][1])
    if (ziplist[i][0] is None) and (ziplist[i][1] is not None):
        print(
            "For element at index {}, {} , no corresponding match found in lst1".format(
                i, ziplist[i][1]
            )
        )
    elif (ziplist[i][0] is not None) and (ziplist[i][1] is None):
        print(
            "For element at index {}, {} , no corresponding match found in lst1".format(
                i, ziplist[i][0]
            )
        )
    elif ziplist[i][0] == ziplist[i][1]:
        print(
            "match found between {} and {} at index {} in both lists".format(
                ziplist[i][0], ziplist[i][1], i
            )
        )
    elif ziplist[i][0] != ziplist[i][1]:
        print("Elements at index {} do not match".format(i))

我在此处将zip_longest(lst1, lst2, fillvalue=None)填充值用作“无”,但是您可以根据列表中的数据使用所需的任何填充值,以便您可以轻松识别是否不存在。您可以了解有关itertools.zip_longest() here的更多信息。