Compare two lists A, B in Python find all elements in A which correspond to the same number in B

后端 未结 5 810
无人共我
无人共我 2021-01-21 04:42

I want to compare two Python lists, \'A\' and \'B\' in such a manner that I can find all elements in A which correspond to the same number in B

5条回答
  •  再見小時候
    2021-01-21 05:40

    I think you can use this code:

    A = [5, 7, 9, 12, 8, 16, 25]
    B = [2, 1, 3, 2, 3, 1, 4]
    
    d = {}
    
    for a, b in zip(A, B):
        d.setdefault(b, [])
        d[b].append(a)
    
    for k, v in sorted(d.items()):
        print('{} corresponds {}'.format(v, k))
    

    Each key of the dictionary will be an element of B, and its associated value will be the list you want.

提交回复
热议问题