简体   繁体   中英

Pythonic way to find all the different intersections and differences between two lists of arrays

This is the generalization of a previous question of mine. I need to find all the intersections and differences between two lists of different arrays. There are no intersections within the arrays of any of the lists, only between the arrays in different lists.

The expected result for the next example

x = [np.array([0, 6, 7, 10]), np.array([1, 2, 5, 9])]
y = [np.array([ 7, 10]), np.array([8]), np.array([0, 3, 4, 5])]

should be

[[0], [6], [7, 10], [1, 2, 9], [5], [8], [3, 4]]

Any suggestion? Thanks in advance!

There is no point to separate arguments, the result will be the same as you unite x and y . So you have set of sets and try to find separate pieces. To find them you can iterate through all elements and remember at which sets this value was encountered. Then if 2 elements have exactly the same set of sets (say they both met at second and forth sets) we return this elements as united group.

from collections import defaultdict


def pythonic(s):
    """
    >>> pythonic([[0, 6, 7, 10], [1, 2, 5, 9], [7, 10], [0, 3, 4, 5]])
    [[0], [6], [7, 10], [1, 2, 9], [5], [3, 4]]
    >>> pythonic([[7, 10], [8], [0, 3, 4, 5], [0, 6, 7, 10], [1, 2, 5, 9]])
    [[7, 10], [8], [0], [3, 4], [5], [6], [1, 2, 9]]
    >>> pythonic([[0, 1, 4, 5], [1, 2, 3, 4], [3, 4, 5, 6]])
    [[0], [1], [4], [5], [2], [3], [6]]
    """
    all_elements = defaultdict(list)
    for i, ss in enumerate(s):
        for elem in ss:
            all_elements[elem].append(i)
    reversed = defaultdict(list)
    for k, v in all_elements.items():
        reversed[frozenset(v)].append(k) # or tuple can be used but "frozenset" feels "safer"
    return list(reversed.values())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM