Comparing two lists in Python

后端 未结 4 563
旧时难觅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:07

    i think this is what u want ask me anything about it i will try to answer it

        listA = ['a', 'b', 'c']
    listB = ['a', 'h', 'c']
    new1=[]
    for a in listA:
        if a in listB:
            new1.append(a)
    
    john = 'I love yellow and green'
    mary = 'I love yellow and red'
    j=john.split()
    m=mary.split()
    new2 = []
    for a in j:
        if a in m:
            new2.append(a)
    x = " ".join(new2)
    print(x)
    
    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2020-12-30 11:10

    If the two lists are the same length, you can do a side-by-side iteration, like so:

    list_common = []
    for a, b in zip(list_a, list_b):
        if a == b:
            list_common.append(a)
    
    0 讨论(0)
  • 2020-12-30 11:17

    Intersect them as sets:

    set(listA) & set(listB)
    
    0 讨论(0)
提交回复
热议问题