栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

计算python dicitonary / array数据结构的非空末页-递归算法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算python dicitonary / array数据结构的非空末页-递归算法?

也许这可以指导您正确的方向。

byPath
收集嵌套的字典项。调用之后,您基本上可以将结果列表弄平,并检查是否满足您的条件(例如
elem !=''
或类似条件
not elem
):

x = #your x as posteddef 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') )

编辑 :这部分实际计数那些不是空字符串的元素:

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) )

将所有内容放在一起:

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) )


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/625474.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号