Python - Compare two lists in a comprehension

后端 未结 3 950
南方客
南方客 2020-12-10 08:01

I\'m trying to understand how comprehensions work.

I would like to loop through two lists, and compare each to find differences. If one/or-more word(s) is different,

3条回答
  •  心在旅途
    2020-12-10 08:43

    If you want to compare two lists for differences, I think you want to use a set.

    s.symmetric_difference(t)   s ^ t   new set with elements in either s or t but not both
    

    example:

    >>> L1 = ['a', 'b', 'c', 'd']
    >>> L2 = ['b', 'c', 'd', 'e'] 
    >>> S1 = set(L1)
    >>> S2 = set(L2)
    >>> difference = list(S1.symmetric_difference(S2))
    >>> print difference
    ['a', 'e']
    >>> 
    

    one-line form?

    >>> print list(set(L1).symmetric_difference(set(L2)))
    ['a', 'e']
    >>> 
    

    if you really want to use a list comprehension:

    >>> [word for word in L1 if word not in L2] + [word for word in L2 if word not in L1]
    ['a', 'e']
    

    much less efficient as the size of the lists grow.

提交回复
热议问题