python-嵌套数组的对比(数组嵌套字典,再嵌套数组..)

需求是对两个嵌套数字进行对比,判断两个数组的内容是否是一样的。

数据长这样


[{'type': 4, 'pos': [403, 323, 563, 352], 'content': '0'}, {'type': 4, 'pos': [492, 572, 609, 630], 'content': '0'}, {'type': 4, 'pos': [412, 740, 532, 798], 'content': '0'}, {'type': 4, 'pos': [112, 807, 178, 865], 'content': '0'}, {'type': 4, 'pos': [82, 1060, 1107, 1432], 'content': '1'}, {'type': 3, 'pos': [82, 1060, 1107, 1432], 'content': '-2'}, {'type': 7, 'pos': [], 'content': '09.07'}, {'type': 2, 'pos': [], 'content': '2'}]
[{'type': 4, 'pos': [112, 807, 178, 865], 'content': '0'}, {'type': 4, 'pos': [82, 1060, 1107, 1432], 'content': '1'}, {'type': 3, 'pos': [82, 1060, 1107, 1432], 'content': '-2'}, {'type': 4, 'pos': [403, 323, 563, 352], 'content': '0'}, {'type': 4, 'pos': [492, 572, 609, 630], 'content': '0'}, {'type': 4, 'pos': [412, 740, 532, 798], 'content': '0'}, {'type': 7, 'pos': [], 'content': '09.07'}, {'type': 2, 'pos': [], 'content': '2'}]

大概有以下几种思路

  • 排序+比较
  • 直接比较(想到两种方法,如果有其他方法,欢迎补充)
    • 使用set
    • 使用in

三种方法都试了:

  1. 本来想排序来着,但里面的嵌套层数太多,无法排序
  2. 可以用set进行比较,set(a)^set(b),但因为里面元素是dict,而dict不支持哈希,报错了。
  3. 后来用了in
    strA = response.json["data"]["answerSheets"]["30371513"]["pages"]["1"]
    strB = [{"type":4,"pos":[112,807,178,865],"content":"0"},{"type":4,"pos":[82,1060,1107,1432],"content":"1"},{"type":3,"pos":[82,1060,1107,1432],"content":"-2"},{"type":4,"pos":[403,323,563,352],"content":"0"},{"type":4,"pos":[492,572,609,630],"content":"0"},{"type":4,"pos":[412,740,532,798],"content":"0"},{"type":7,"pos":[],"content":"09.07"},{"type":2,"pos":[],"content":"2"}]
    res = True
    diff = []
    for i in range(0, len(strA)):
        if(strA[i] not in strB):
            diff.append(strA[i])
            res = False

你可能感兴趣的:(Python,python)