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

后端 未结 5 773
无人共我
无人共我 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:27

    An alternative using collections.defaultdict:

    import collections as ct
    
    dd = ct.defaultdict(list)
    for a, b in zip(A, B):
        dd[b].append(a)
    
    dd
    # defaultdict(list, {1: [7, 16], 2: [5, 12], 3: [9, 8], 4: [25]})
    

    Sample of printed results:

    for k, v in sorted(dd.items()):
        print("{} corresponding to the number {} of listB".format(v, k))
    
    # [7, 16] corresponding to the number 1 of listB
    # [5, 12] corresponding to the number 2 of listB
    # [9, 8] corresponding to the number 3 of listB
    # [25] corresponding to the number 4 of listB
    

提交回复
热议问题