简体   繁体   中英

How to compare array of arrays in Python?

I have 2 lists like the following:

a=[[1,0,1,0,1],[0,0,0,1,0],[1,1,0,0,0]]
b=[[1,0,0,0,1],[0,1,0,1,0],[1,1,0,1,0]]

I want to return true if all the sublists in b are present in a and vice versa. That means a should be equal to b but indexes of the sublists can be different. eg:

a=[[1,0,1,0,1],[0,0,0,1,0],[1,1,0,0,0]]
b=[[1,0,1,0,1],[1,1,0,0,0],[0,0,0,1,0]]

Above a and b are equal and comparison should return true. Also, the sublists will only contain a combination of 1s or 0s. How do I compare them? I tried converting them to sets : set(a) but this is throwing an error. Apart from that, when I tried the following code in a while loop, it gave an error

a=[[1,0,1,0,1],[0,0,0,1,0],[1,1,0,0,0]]
b=[[1,0,1,0,1],[1,1,0,0,0],[0,0,0,1,0]]

def sublists_equal(a, b):
    return all(l for l in b if l in a)

print(sublists_equal(a, b))

The error was:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I tried printing both the arrays to see what the problem was, they are printing like follows:

[[0 1 0 1 0]
 [0 1 1 1 1]
 [0 0 0 0 1]
 [0 1 0 0 0]]
[array([0, 1, 0, 1, 0]), array([0, 0, 0, 0, 1]), array([0, 1, 1, 1, 1]), array([0, 1, 0, 0, 0])]

I hope this code help you

a=[[1,0,1,0,1],[0,0,0,1,0],[1,1,0,0,0]]
b=[[1,1,0,0,0],[1,0,1,0,1],[0,0,0,1,0]]
c=[[1,1,0,0,0],[1,1,1,0,1],[0,0,0,1,0]]

def check(a,b):
    status = True
    for i in a:
        if i not in b:
            status = False
            break
    return(status)
    
print(check(a,b))
print(check(a,c))

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