How can I compare two lists in python and return matches

后端 未结 19 2334
误落风尘
误落风尘 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:04

    Do you want duplicates? If not maybe you should use sets instead:

    >>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5]))
    set([5])
    
    0 讨论(0)
  • 2020-11-22 05:06
    >>> s = ['a','b','c']   
    >>> f = ['a','b','d','c']  
    >>> ss= set(s)  
    >>> fs =set(f)  
    >>> print ss.intersection(fs)   
       **set(['a', 'c', 'b'])**  
    >>> print ss.union(fs)        
       **set(['a', 'c', 'b', 'd'])**  
    >>> print ss.union(fs)  - ss.intersection(fs)   
       **set(['d'])**
    
    0 讨论(0)
  • 2020-11-22 05:06

    You can use:

    a = [1, 3, 4, 5, 9, 6, 7, 8]
    b = [1, 7, 0, 9]
    same_values = set(a) & set(b)
    print same_values
    

    Output:

    set([1, 7, 9])
    
    0 讨论(0)
  • 2020-11-22 05:07
    you can | for set union and & for set intersection.
    for example:
    
        set1={1,2,3}
        set2={3,4,5}
        print(set1&set2)
        output=3
    
        set1={1,2,3}
        set2={3,4,5}
        print(set1|set2)
        output=1,2,3,4,5
    
    curly braces in the answer.
    
    0 讨论(0)
  • 2020-11-22 05:08

    I prefer the set based answers, but here's one that works anyway

    [x for x in a if x in b]
    
    0 讨论(0)
  • 2020-11-22 05:10
    a = [1, 2, 3, 4, 5]
    b = [9, 8, 7, 6, 5]
    
    lista =set(a)
    listb =set(b)   
    print listb.intersection(lista)   
    returnMatches = set(['5']) #output 
    
    print " ".join(str(return) for return in returnMatches ) # remove the set()   
    
     5        #final output 
    
    0 讨论(0)
提交回复
热议问题