V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
szxczyc
V2EX  ›  问与答

迫于老年人记忆力,请问 Python 里两个判断可以有一个返回值吗?

  •  
  •   szxczyc · 2021-11-02 04:26:10 +08:00 · 1277 次点击
    这是一个创建于 903 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    #json 处理函数
    def get_json_data(data,query_type,query_name):
        before_json_txt = data.text
        json_mid = json.loads(before_json_txt)
        result = json_mid['data']['result']
        if query_type == 'usage':
            for i in range(len(result)):#取最大值
                list = []
                list.append(round(float(result[i]['value'][1]),4))
            max_result = max(list)
            return max_result
        elif query_type == 'qps':#为 qps 时只保留整数且匹配 cmd 名
            for i in result:#取最大值
                if i["metric"]["cmd"]== query_name:
                    max_result = round(i['value'][1])
            return max_result
    
    

    请问我该怎么样才能让这个函数能根据usageqps的情况,并且返回值都为max_result呢?

    3 条回复    2021-11-02 09:55:12 +08:00
    lzdhlsc
        1
    lzdhlsc  
       2021-11-02 04:38:46 +08:00
    如果没理解错的话,这段代码逻辑上好像没什么问题。只需要在 `if ... elif ...` 后面加一个 `else` 然后 `raise` exception 来处理 `query_type` 其他的情况就好了。
    ladypxy
        2
    ladypxy  
       2021-11-02 08:29:35 +08:00
    代码看上去没大问题
    其实可以把 2 个 return 放到 if elif 外面
    harryhao
        3
    harryhao  
       2021-11-02 09:55:12 +08:00   ❤️ 1
    在函数开头声明 max_result 变量,比如 max_result = None
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3571 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 11:05 · PVG 19:05 · LAX 04:05 · JFK 07:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.