【问题标题】:how to find index by value in json nested python [closed]如何在json嵌套python中按值查找索引[关闭]
【发布时间】:2021-07-30 14:21:46
【问题描述】:
body = {
    'a': 1,
    'b': 'apple',
    'child': [
        {
            'a': 12,
            'b': 'banana',
            'child': [
                {
                    'a': 121,
                    'b': 'mango',
                    'child': [
                        {
                            'a': 1211,
                            'b': 'coconut',
                            'child': [dynamic nested]
                        }
                    ]
                },
                {
                    'a': 122,
                    'b': 'papaya',
                    'child': [
                        {
                            'a': 1221,
                            'b': 'lemon',
                            'child': [dynamic nested]
                        }
                    ]
                }
            ]
        },
        {
            'a': 13,
            'b': 'orenge',
            'child': [
                dynamic nested
            ]
        }
    ]
}

如果我想知道 'coconut' 或 'lemon' 的索引(json body dynamic children sub child 我不知道 dee child,但是 khow 'a' or 'b' for find index deep)

如何用python获取索引?

ex1: index of 'coconut' = [0,0,0]
ex2: index of 'lemon' = [0,1,0]

【问题讨论】:

标签: python python-3.x


【解决方案1】:
def find(child, value, index=False):
     # First element in nested object is searched value
     if child["b"] == value:
         return []
     if len(child["child"]) == 0:
         return False
     for i in range(len(child["child"])):
         if child["child"][i]["b"] == value:
             index = [i]
             break
         else:
             index = find(child["child"][i], value, index)
             if index != False:
                  index = [i] + index
                 break
     return index
print(find(body, "coconut"))

使用递归函数

【讨论】:

  • 如果 index != False:= TypeError: can only concatenate list (not "NoneType") to list 我试试这个代码抛出行
  • 取消最后一个“返回索引”一次
【解决方案2】:

出于教育目的,Akane 的算法相同,但更 Pythonic 风格:

def find_fruit(child, value, index=False):
    if child["b"] == value: 
        return []
    for i, ch in enumerate(child["child"]):
        if ch["b"] == value: 
            return [i]
        index = find_fruit(ch, value, index)
        if index: 
            return [i] + index

print(find(body, "coconut"))

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多