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

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

    You can use zip to create tuples which consist from one element from both lists, then sort them and finally group them by value from B:

    >>> from itertools import groupby
    >>> A = [5, 7, 9, 12, 8, 16, 25]
    >>> B = [2, 1, 3, 2, 3, 1, 4]
    >>> for k, g in groupby(sorted(zip(B,A)), key=lambda x: x[0]):
    ...     print('{} corresponds to {}'.format([x[1] for x in g], k))
    ... 
    [7, 16] corresponds to 1
    [5, 12] corresponds to 2
    [8, 9] corresponds to 3
    [25] corresponds to 4
    

    In above zip(B, A) returns iterable of tuples where each tuple has element from B and A:

    >>> list(zip(B,A))
    [(2, 5), (1, 7), (3, 9), (2, 12), (3, 8), (1, 16), (4, 25)]
    

    Result of above is then sorted so that all the tuples with same value from B are next to each other:

    >>> sorted(zip(B,A))
    [(1, 7), (1, 16), (2, 5), (2, 12), (3, 8), (3, 9), (4, 25)]
    

    Result of sorting is passed to groupby which groups the tuples based on value returned by key function, in this case the first item in the tuple. Result is iterable of (key, group) tuples where group is iterable of elements:

    >>> [(k, list(g)) for k, g in groupby(sorted(zip(B,A)), key=lambda x: x[0])]
    [(1, [(1, 7), (1, 16)]), (2, [(2, 5), (2, 12)]), (3, [(3, 8), (3, 9)]), (4, [(4, 25)])]
    

提交回复
热议问题