zoukankan      html  css  js  c++  java
  • 递归查找小练习

    递归小练习

    #!/usr/bin/env/python
    #-*- coding:utf-8 -*-
    
    def findkeyvalue(keyname,target):
    """
    使用递归方式在字典列表混合数据中查找指定key的值
    只返回第一个符合的键值
    find the first key's value in mix dict and list via recursion
    :param keyname: key name (string)
    :param tagetr: data (dict or list or both)
    :return: the key's value
    """
        if isinstance(target,dict) and keyname in target:
            return target[keyname]
        if isinstance(target,dict) and keyname not in target:
            target = list(target.values())
        if isinstance(target,list):
            for i in target:
                if isinstance(i,dict) or isinstance(i,list):
                    value = findkeyvalue(keyname,i)
                    if value is not None:
                        return value
    if __name__ == '__main__':
    
        bb = [
            [1, 2, 3, 4],
            [{'a': 'a', 'b': 'b'}, [12, 3], {'c': 1, 'd': [1, 2, {'e': [{'c': 1}]}, 4]}],
            {'a': {'a': {'a': 1}}, 'b': [432, 54]},
            [{'a': 1}, {'b': 2}, [{'c': 3}, {'a': 'cc', 'b': [1, {'cici': 'check'}]}]],
            [3, 4, 5],
            {'cici': 'bb'}
        ]
        print(findkeyvalue('cici', bb))
  • 相关阅读:
    ElementUI Form 表单
    ElementUI 快速入门
    您即将提交的信息不安全
    pandas excel合并去重
    openpyxl刷新透视表
    安装kube-prometheus
    多个py文件生成一个可运行exe文件
    Locust关联和参数化
    使用Docker运行locust
    Python locust阶段压测
  • 原文地址:https://www.cnblogs.com/liao-lin/p/7126123.html
Copyright © 2011-2022 走看看