首页 > 解决方案 > 匹配两个列表之间的元素,但索引为索引

问题描述

可以说我有这两个列表:

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

lst2 = ['A1','B2']

对于 lst1 中的每个元素,按索引与 lst2 中的相应元素进行比较(1-1 而不是元素 1 到 lst2 中的所有元素)。如果找到匹配项,则打印如下输出:'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...'

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

标签: python

解决方案


试试这个:

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.

推荐阅读