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

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

    A = [5, 7, 9, 12, 8, 16, 25]
    B = [2, 1, 3, 2, 3, 1, 4]
    

    Create a specific function that takes two lists (A, B) and a number (n) as arguments. Select all items in A that have the same list position as the items in B that are equivalent to n. zip is used to pair items from A and B with the same list position. This function uses a list comprehension to select the items from A.

    >>> def f(A, B, n):
        return [a for a, b in zip(A,B) if b == n]
    
    >>> f(A, B, 2)
    [5, 12]
    >>> 
    

    The function could be written without a list comprehension:

    def g(A, B, n):
        result = []
        for a, b in zip(A, B):
            if b == n:
                result.append(a)
        return result
    

    Using fuctools.partial the list arguments can be fixed:

    import functools
    f_AB = functools.partial(f, A, B)
    

    Then it could be used like this:

    >>> f_AB(3)
    [9, 8]
    
    >>> numbers = [3, 4, 2]
    >>> for n in numbers:
        print (n, f_AB(n))
    
    (3, [9, 8])
    (4, [25])
    (2, [5, 12])
    >>>
    

提交回复
热议问题