How can I compare two lists in python and return matches

后端 未结 19 2333
误落风尘
误落风尘 2020-11-22 04:16

I want to take two lists and find the values that appear in both.

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]

returnMatches(a, b)

would return

相关标签:
19条回答
  • 2020-11-22 05:10

    The following solution works for any order of list items and also supports both lists to be different length.

    import numpy as np
    def getMatches(a, b):
        matches = []
        unique_a = np.unique(a)
        unique_b = np.unique(b)
        for a in unique_a:
            for b in unique_b:
                if a == b:
                    matches.append(a)
        return matches
    print(getMatches([1, 2, 3, 4, 5], [9, 8, 7, 6, 5, 9])) # displays [5]
    print(getMatches([1, 2, 3], [3, 4, 5, 1])) # displays [1, 3]
    
    0 讨论(0)
提交回复
热议问题