How can I compare two lists in python and return not matches

前端 未结 5 2061
夕颜
夕颜 2021-02-05 20:16

I would like to return values from both lists that not in the other one:

bar = [ 1,2,3,4,5 ]
foo = [ 1,2,3,6 ]

returnNotMatches( a,b )

would r

相关标签:
5条回答
  • 2021-02-05 20:41

    You could use a list comprehension and zip

    ''.join([i[0] for i in zip(a, a.lower()) if i[0] == i[1]])
    
    0 讨论(0)
  • 2021-02-05 20:46

    This should do

    def returnNotMatches(a, b):
        a = set(a)
        b = set(b)
        return [list(b - a), list(a - b)]
    

    And if you don't care that the result should be a list you could just skip the final casting.

    0 讨论(0)
  • 2021-02-05 20:51

    One of the simplest and quickest is:

    new_list = list(set(list1).difference(list2))
    
    0 讨论(0)
  • 2021-02-05 20:54

    Just use a list comprehension:

    def returnNotMatches(a, b):
        return [[x for x in a if x not in b], [x for x in b if x not in a]]
    
    0 讨论(0)
  • 2021-02-05 21:00

    I might rely on the stdlib here...

    from itertools import tee, izip
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return izip(a, b)
    
    import difflib
    
    def returnNotMatches(a, b):
        blocks = difflib.SequenceMatcher(a=a, b=b).get_matching_blocks()
        differences = []
        for b1, b2 in pairwise(blocks):
            d1 = a[b1.a + b1.size: b2.a]
            d2 = b[b1.b + b1.size: b2.b]
            differences.append((d1, d2))
        return differences
    
    print returnNotMatches([ 1,2,3,4,5 ], [ 1,2,3,6 ])
    

    which prints: [([4, 5], [6])]

    This compares the sequences as streams and finds the differences in the streams. It takes order into account, etc. If order and duplicates don't matter, then sets are by far the way to go (so long as the elements can be hashed).

    0 讨论(0)
提交回复
热议问题