我正在解析未知的嵌套json对象,我不知道结构和深度提前。我正在尝试搜索它以找到一个值。这是我想出来的,但我觉得很无聊。有人能告诉我怎么让这个看起来更像Python,更干净吗?在
def find(d, key):
if isinstance(d, dict):
for k, v in d.iteritems():
try:
if key in str(v):
return 'found'
except:
continue
if isinstance(v, dict):
for key,value in v.iteritems():
try:
if key in str(value):
return "found"
except:
continue
if isinstance(v, dict):
find(v)
elif isinstance(v, list):
for x in v:
find(x)
if isinstance(d, list):
for x in d:
try:
if key in x:
return "found"
except:
continue
if isinstance(v, dict):
find(v)
elif isinstance(v, list):
for x in v:
find(x)
else:
if key in str(d):
return "found"
else:
return "Not Found"
使用duck类型通常更“python”;也就是说,只需尝试搜索目标而不是使用
isinstance
。见What are the differences between type() and isinstance()?但是,由于需要递归,因此有必要递归字典和列表元素的值。(是否也要搜索词典的关键字?)在
in
运算符可以同时用于字符串、列表和字典,因此在测试成员身份时不需要将字典与列表分开。假设您不想将目标作为子字符串进行测试,请按照上一个链接使用isinstance(basestring)
。要测试目标是否在字典的值中,请测试your_dictionary.values()
中的成员资格。见Get key by value in dictionary因为dictionary值可能是list或dictionary,所以我仍然可以像您那样测试dictionary和list类型,但是我提到,您可以用一个语句同时覆盖list元素和dictionary key,因为您要问的是python,在两种类型中使用重载的oeprator,如
in
,这是典型的Python。在你使用递归的想法是必要的,但是我不会用
find
来定义函数,因为这是一个Python内置函数,你会(某种程度上)隐藏递归调用,使递归调用的可读性变差,因为另一个程序员可能会误认为你在调用内置函数(作为一个好的实践,您可能希望保留对内置的常规访问,以防调用它。)要测试数字类型,请使用`数字。数字'如How can I check if my python object is a number?所述
另外,在https://gist.github.com/douglasmiranda/5127251有一个问题的变体的解决方案。我发现这是因为ColdSpeed在评论中的regex建议让我怀疑我是不是在引导你走上了错误的道路。在
所以有点像
相关问题 更多 >
编程相关推荐