在复杂的JSON数组和哈希中搜索项目时,例如:
[
{ "id": 1, "name": "One", "objects": [
{ "id": 1, "name": "Response 1", "objects": [
// etc.
}]
}
]
Run Code Online (Sandbox Code Playgroud)
我可以用某种查询语言来查找项目in [0].objects where id = 3吗?
我有一个这样的字典:
{ "id" : "abcde",
"key1" : "blah",
"key2" : "blah blah",
"nestedlist" : [
{ "id" : "qwerty",
"nestednestedlist" : [
{ "id" : "xyz",
"keyA" : "blah blah blah" },
{ "id" : "fghi",
"keyZ" : "blah blah blah" }],
"anothernestednestedlist" : [
{ "id" : "asdf",
"keyQ" : "blah blah" },
{ "id" : "yuiop",
"keyW" : "blah" }] } ] }
Run Code Online (Sandbox Code Playgroud)
基本上是具有任意深度的嵌套列表,字典和字符串的字典.
遍历此方法以提取每个"id"键的值的最佳方法是什么?我想实现相当于XPath查询,如"// id"."id"的值始终是一个字符串.
所以从我的例子来看,我需要的输出基本上是:
["abcde", "qwerty", "xyz", "fghi", "asdf", "yuiop"]
Run Code Online (Sandbox Code Playgroud)
订单并不重要.
我在Python 3.2中有一个代码,我想在Python 2.7中运行它.我确实转换了它(已经把missing_elements两个版本的代码都放了)但我不确定这是否是最有效的方法.基本上如果yield from在missing_element功能的上半部分和下半部分有两个如下所示的调用会发生什么?两个部分(上部和下部)中的条目是否在一个列表中相互附加,以便父级递归函数与yield from调用一起使用并将两个部分一起使用?
def missing_elements(L, start, end): # Python 3.2
if end - start <= 1:
if L[end] - L[start] > 1:
yield from range(L[start] + 1, L[end])
return
index = start + (end - start) // 2
# is the lower half consecutive?
consecutive_low = L[index] == L[start] + (index - start)
if not consecutive_low:
yield from missing_elements(L, start, index)
# is the upper part consecutive?
consecutive_high = L[index] …Run Code Online (Sandbox Code Playgroud) 我有一些像这样的Python词典:
A = {id: {idnumber: condition},....
Run Code Online (Sandbox Code Playgroud)
例如
A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
Run Code Online (Sandbox Code Playgroud)
我需要搜索字典中是否有任何字典idnumber == 11并使用condition.但如果在整个字典中没有idnumber == 11,我需要继续下一个字典.
这是我的尝试:
for id, idnumber in A.iteritems():
if 11 in idnumber.keys():
calculate = ......
else:
break
Run Code Online (Sandbox Code Playgroud) python ×3
dictionary ×2
recursion ×2
generator ×1
javascript ×1
json ×1
nested ×1
python-2.x ×1
traversal ×1
xpath ×1
xquery ×1
yield ×1
yield-from ×1