Home > Blockchain >  How to match 2 two multi-dimensional list or array
How to match 2 two multi-dimensional list or array

Time:01-28

I am having a bit of trouble finding a code to match 2 two multi-dimensional list or array over 21 rows. For example a1 to find a match in b1 and return the result.

a1 = [
    [
        [91,15,25], [4,14,25]
    ],
    [
        [91,115,215], [41,154,148]
    ]
]


b1 = [
    [
        [41,4,14], [3,5,14]
    ],
    [
        [266,41,73], [366,13,91]
    ]
]

I have tried to use this code but only works by slicing the index which is time consuming. Is there another option specially with a large list.

for l in a1[0]:
    result = []
    for k in b1[0]:
        result.append(list(set(l) & set(k)))
    print(result)

for l in a1[1]:
    result = []
    for k in b1[1]: 
        result.append(list(set(l) & set(k)))
    print(result)

If possible I would like my output to be

result1 = [[[],[],[4, 14], [14]],
        [[],[91],[41],[]]]

then I would like to remove the duplicates.

   result2 = [[[4, 14], [14]],
        [[91], [41]]]

CodePudding user response:

You didn't answer either of my questions, in the comments, so I'm only willing to invest the time to answer half of the question...

Instead of looping, you can use list comprehensions. (In this case, a comprehension within another comprehension.)

It does not "remove duplicates".

l = \
[
    [
        list(
            set(a_) & set(b_)
        )
        for a_ in a
        for b_ in b
    ]
    for (a, b) in zip(a1, b1)
]

print(l)

Demo; https://www.mycompiler.io/new/python?fork=9DHnT2L7mtW

  • Related