首页 > 解决方案 > 嵌套结构比较

问题描述

我正在尝试使用递归编写嵌套结构比较。看起来很基本但不起作用:当我比较它们时len(original)len(other)它们是不同的,但事实并非如此return False。为什么?

def same_structure_as(original,other):
    if type(original) != type(other) or len(original) != len(other):
        return False
    for i in range(len(original)):
        if type(original[i]) != type(other[i]):
            return False
        if type(original[i]) is list and type(other[i]) is list:
            same_structure_as(original[i],other[i])
    return True

print (same_structure_as([1,[1,1]], [2,[2]]))

标签: pythonrecursionnestedcomparison

解决方案


正如所评论的,您的代码没有考虑递归结果。我更正了它并使用了组合循环而不是重复繁琐的索引。(我仍然不喜欢多重返回结构)。请注意,您不会在循环中比较简单值,因此仍然需要用于列表类型比较的 else 部分。否则,这将按预期工作:

   def same_structure_as(original, other):
       if type(original) != type(other) or len(original) != len(other):
           return False
       for org_val, other_val in zip(original, other):
           if type(org_val) != type(other_val):
               return False
           if type(org_val) is list and type(other_val) is list:
               if not same_structure_as(org_val, other_val):
                   return False
       return True

   print (same_structure_as([1,[1,1]], [2,[2]]))

推荐阅读