Pythonic way to compare two lists and print out the differences

前端 未结 7 1724
滥情空心
滥情空心 2021-02-07 10:52

I have two lists which are guaranteed to be the same length. I want to compare the corresponding values in the list (except the first item) and print out the ones which dont mat

相关标签:
7条回答
  • 2021-02-07 11:10

    There's a nice class called difflib.SequenceMatcher in the standard library for that.

    0 讨论(0)
  • 2021-02-07 11:11

    You can use set operation to find Symmetric difference (^) between two lists. This is one of the best pythonic ways to do this.

    list1=[1,2,3,4]
    list2=[1,5,3,4]
    
    print(set(list1) ^ set(list2))
    

    So the output will be {2, 5}

    0 讨论(0)
  • 2021-02-07 11:16

    You could use sets:

    >>> list1=[1,2,3,4]
    >>> list2=[1,5,3,4]
    >>> set(list1[1:]).symmetric_difference(list2[1:])
    set([2, 5])
    
    0 讨论(0)
  • 2021-02-07 11:20

    Nobody's mentioned filter:

    a = [1, 2, 3]
    b = [42, 3, 4]
    
    aToCompare = a[1:]
    bToCompare = b[1:]
    
    c = filter( lambda x: (not(x in aToCompare)), bToCompare)
    print c
    
    0 讨论(0)
  • 2021-02-07 11:27

    Noting the requirement to skip the first line:

    from itertools import izip
    both = izip(list1,list2)
    both.next()  #skip the first
    for p in (p for p in both if p[0]!=p[1]):
       print pair
    
    1. This uses izip, an iterator (itertools) version of zip, to generate an iterator through pairs of values. This way you don't use up a load of memory generating a complete zipped list.
    2. It steps the both iterator by one to avoid processing the first item, and to avoid having to make the index comparison on every step through the loop. It also makes it cleaner to read.
    3. Finally it steps through each tuple returned from a generator which yields only unequal pairs.
    0 讨论(0)
  • 2021-02-07 11:31
    list1=[1,2,3,4]
    list2=[1,5,3,4]
    print [(i,j) for i,j in zip(list1,list2) if i!=j]
    

    Output:

    [(2, 5)]
    

    Edit: Easily extended to skip n first items (same output):

    list1=[1,2,3,4]
    list2=[2,5,3,4]
    print [(i,j) for i,j in zip(list1,list2)[1:] if i!=j]
    
    0 讨论(0)
提交回复
热议问题