python - 嵌套结构比较
问题描述
我正在尝试使用递归编写嵌套结构比较。看起来很基本但不起作用:当我比较它们时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]]))
解决方案
正如所评论的,您的代码没有考虑递归结果。我更正了它并使用了组合循环而不是重复繁琐的索引。(我仍然不喜欢多重返回结构)。请注意,您不会在循环中比较简单值,因此仍然需要用于列表类型比较的 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]]))
推荐阅读
- ios - 使用通用链接在我的会议应用程序中打开 jitsi 视频,但它只打开我的 App.not 会议
- amazon-web-services - EKS 节点组真的有必要吗
- xcode - 如何从 Xcode 打开现有的颤振项目?
- javascript - 如果文件名仅匹配字符串的一部分,则链接到文件
- javascript - JavaScript:无法设置搜索逻辑
- wordpress - 有没有办法为 gatsby-source-wordpress 中的所有内联图像设置“加载:惰性”而不是默认的“加载:渴望”?
- node.js - 命令“ng serve”在命令提示符下工作,但对同一项目的代码不起作用
- wireshark - 从 pcap 卸载协议
- amazon-web-services - VS Code 和 AWS SAM 本地调用问题
- php - 联系表格不适用于 PHP 7.4 版