Get difference between two lists

前端 未结 27 2801
傲寒
傲寒 2020-11-21 11:36

I have two lists in Python, like these:

temp1 = [\'One\', \'Two\', \'Three\', \'Four\']
temp2 = [\'One\', \'Two\']

I need to create a third

27条回答
  •  既然无缘
    2020-11-21 11:49

    Here are a few simple, order-preserving ways of diffing two lists of strings.

    Code

    An unusual approach using pathlib:

    import pathlib
    
    
    temp1 = ["One", "Two", "Three", "Four"]
    temp2 = ["One", "Two"]
    
    p = pathlib.Path(*temp1)
    r = p.relative_to(*temp2)
    list(r.parts)
    # ['Three', 'Four']
    

    This assumes both lists contain strings with equivalent beginnings. See the docs for more details. Note, it is not particularly fast compared to set operations.


    A straight-forward implementation using itertools.zip_longest:

    import itertools as it
    
    
    [x for x, y in it.zip_longest(temp1, temp2) if x != y]
    # ['Three', 'Four']
    

提交回复
热议问题