簡體   English   中英

匹配兩個列表之間的元素,但索引為索引

[英]Match elements between two lists but index for index

可以說我有這兩個列表:

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

lst2 = ['A1','B2']

對於 lst1 中的每個元素,按索引與 lst2 中的相應元素進行比較(1-1 而不是元素 1 到 lst2 中的所有元素)。 如果找到匹配項,則打印 output 如下所示: 'match found between A1 and A1 at index 0 in both lists'

如果元素與 output 不匹配,應該給出這樣的: '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...'

當列表的長度不匹配時,它會失敗,除此之外,我確信有一種更聰明的方法可以做到這一點。

嘗試這個:

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]}")

這將產生這個 output:

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.

在這種情況下,我會敦促您使用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) fillvalue as None 但是您可以根據列表中的數據使用您想要的任何填充值,這樣您就可以輕松識別是否存在某些內容。 您可以在此處閱讀有關itertools.zip_longest()的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM