Count non-empty end-leafs of a python dicitonary/array data structure - recursive algorithm?

后端 未结 1 1250
春和景丽
春和景丽 2021-01-15 23:32

I\'m looking for a function to find all the non-empty end-points of a kind of complex dictionary/array structure. I think that because I don\'t know the number of nested ar

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 23:34

    Maybe this can guide you in the right direction. byPath collects the nested dictionary items. Once called, you can basically flatten out the resulting list and check if your condition is met (like elem != '' or not elem or whatever):

    x = #your x as posted
    
    def byPath (tree, path):
        try: head, tail = path.split ('.', 1)
        except: return tree [path]
    
        if head == 'XX': return [byPath (node, tail) for node in tree]
        else: return byPath (tree [head], tail)
    
    
    print (byPath (x, 'top.middle.XX.nested') )
    print (byPath (x, 'top.last.XX.nested.XX.first') )
    print (byPath (x, 'top.last.XX.nested.XX.second') )
    print (byPath (x, 'other') )
    

    EDIT: Here the part for actually counting those elements that are not an empty string:

    def count (result):
        if isinstance (result, list):
            total = 0
            positive = 0
            for e in result:
                r = count (e)
                total += r [1]
                positive += r [0]
            return (positive, total)
        else: return (0 if result == '' else 1, 1)
    
    a = byPath (x, 'top.middle.XX.nested')
    b = byPath (x, 'top.last.XX.nested.XX.first')
    c = byPath (x, 'top.last.XX.nested.XX.second')
    d = byPath (x, 'other')
    
    for x in [a, b, c, d]: print (count (x) )
    

    Putting everything together:

    def f (tree, path):
        return count (byPath (tree, path) )
    
    for path in ['top.middle.XX.nested', 'top.last.XX.nested.XX.first', 'top.last.XX.nested.XX.second', 'other']:
        print (path, f (x, path) )
    

    0 讨论(0)
提交回复
热议问题