如何在python元素中比较两个2d列表?

问题描述 投票:0回答:1

我有两个二维列表:两者的大小均相同,但大小未知(针对不同的列表集而有所不同)

例如:

A = [['ID', 'Name', 'Profession'], [1, 'Tom', 'Teacher'], [2, 'Dick', 'Actor'], [3, 'Harry', 'Lawyer']]

B = [['ID', 'Name', 'Profession'], [1, 'Tom', 'Police'], [2, 'Dick', 'Actor'], [3, 'Harry', 'Lawyer']]

我想对所有元素的文件元素进行明智的比较(例如:a[0][1] == b[0][1],并使用元素索引打印差异。

我想输出如下内容:

a[0][2] = Teacher <> b[0][1] = Police

如果我可以使用主键(ID)比较列表,以防列表与以下输出不匹配,那就太好了:

Profession of ID = 1 does not match, i.e Teacher <> Police

注意:文件可能非常大(矩阵为100 * 10000)

谢谢。

python arrays list compare difference
1个回答
0
投票

尝试一下:

# If A and B have equal length
for k in range(len(A)):
    i = A[k]
    j = B[k]

    # If the nested lists of both A and B has same length
    l = len(i)-1
    while(l>=0):
        if not i[l] is j[l]:
            print(f"a[{k}][{l}] = {i[l]} <> b[{k}][{l}] = j[l]")
        l -= 1
© www.soinside.com 2019 - 2024. All rights reserved.