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

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

    Try this approach.

    unique = set(B)    # Creates a set of unique entries in B
    for u in unique:
        # Find indices of unique entry u
        indices = [i for i, x in enumerate(B) if x == u]
    
        # Pull out these indices in A
        corrEntry = [A[i] for i in indices]  
    
        # Do something with the data, in this case print what OP wants
        print('{} corresponds to the number {} of list B'.format(corrEntry , B[indices[0]]))
    

    It finds the unique entries in B by using the set function. We then loop through these unique entries. The first list comprehension (for indices) finds the indices of the entries in B that match this unique entry. The second saves the value in A of those indices.

提交回复
热议问题