簡體   English   中英

如何檢查列表元素是否在另一個列表中,但也在同一索引中

[英]how to check whether a list element is in another list but also at the same index

我需要檢查兩個列表是否具有相同的元素,但這些相同的元素也必須位於相同的索引位置。

我想出了一個以下丑陋的解決方案:

def check_any_at_same_index(list_input_1, list_input_2):
    # set bool value
    check_if_any = 0
    for index, element in enumerate(list_input_1):
        # check if any elements are the same and also at the same index position
        if element == list_input_2[index]:
            check_if_any = 1
    return check_if_any

if __name__ == "__main__":
    list_1 = [1, 2, 4]
    list_2 = [2, 4, 1]
    list_3 = [1, 3, 5]

    # no same elements at same index
    print check_any_at_same_index(list_1, list_2)
    # has same element 0
    print check_any_at_same_index(list_1, list_3)

有什么更好的方法可以做到這一點,任何建議?

如果要檢查同一索引中是否存在任何相等的項,則可以在any()使用zip()函數和生成器表達式。

any(i == j for i, j in zip(list_input_1, list_input_2))

如果要返回該項(第一次出現),可以使用next()

next((i for i, j in zip(list_input_1, list_input_2) if i == j), None)

如果你想檢查所有你可以使用一個簡單的比較:

list_input_1 == list_input_2

暫無
暫無

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

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