Python - Compare two lists in a comprehension

后端 未结 3 946
南方客
南方客 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:42

    Like kriegar suggested using sets is probably the easiest solution. If you absolutely need to use list comprehension, I'd use something like this:

    list_1 = [1, 2, 3, 4, 5, 6]
    list_2 = [1, 2, 3, 0, 5, 6]
    
    # Print all items from list_1 that are not in list_2 ()
    print(*[item for item in list_1 if item not in list_2], sep='\n')
    
    # Print all items from list_1 that differ from the item at the same index in list_2
    print(*[x for x, y in zip(list_1, list_2) if x != y], sep='\n')
    
    # Print all items from list_2 that differ from the item at the same index in list_1
    print(*[y for x, y in zip(list_1, list_2) if x != y], sep='\n')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 08:52

    Doing it in "one nice line of code" is code golf, and misguided. Make it readable instead.

    for a, b in zip(list1, list2):
        if a != b:
           print(a, "is different from", b) 
    

    This is not different in any significant way from this:

    [print(a, "is different from", b) for a, b in zip(list1, list2) if a!=b]
    

    Except that the expanded version easier to read and understand than the comprehension.

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