Comparing two lists in Python

后端 未结 4 562
旧时难觅i
旧时难觅i 2020-12-30 10:41

So to give a rough example without any code written for it yet, I\'m curious on how I would be able to figure out what both lists have in common.

Example:

         


        
4条回答
  •  别那么骄傲
    2020-12-30 11:09

    Use set intersection for this:

    list(set(listA) & set(listB))
    

    gives:

    ['a', 'c']
    

    Note that since we are dealing with sets this may not preserve order:

    ' '.join(list(set(john.split()) & set(mary.split())))
    'I and love yellow'
    

    using join() to convert the resulting list into a string.

    --

    For your example/comment below, this will preserve order (inspired by comment from @DSM)

    ' '.join([j for j, m in zip(john.split(), mary.split()) if j==m])
    'I love yellow and'
    

    For a case where the list aren't the same length, with the result as specified in the comment below:

    aa = ['a', 'b', 'c']
    bb = ['c', 'b', 'd', 'a']
    
    [a for a, b in zip(aa, bb) if a==b]
    ['b']
    

提交回复
热议问题