简体   繁体   English

如何比较 Python 中的数组数组?

[英]How to compare array of arrays in Python?

I have 2 lists like the following:我有 2 个列表,如下所示:

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.如果 b 中的所有子列表都存在于 a 中,我想返回 true,反之亦然。 That means a should be equal to b but indexes of the sublists can be different.这意味着 a 应该等于 b 但子列表的索引可以不同。 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.以上 a 和 b 是相等的,比较应该返回 true。 Also, the sublists will only contain a combination of 1s or 0s.此外,子列表将仅包含 1 或 0 的组合。 How do I compare them?我如何比较它们? I tried converting them to sets : set(a) but this is throwing an error.我尝试将它们转换为集合:set(a) 但这会引发错误。 Apart from that, when I tried the following code in a while loop, it gave an error除此之外,当我在 while 循环中尝试以下代码时,它给出了错误

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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