V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
szxczyc
V2EX  ›  问与答

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

  •  
  •   szxczyc · Nov 2, 2021 · 2140 views
    This topic created in 1638 days ago, the information mentioned may be changed or developed.
    
    #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 replies    2021-11-02 09:55:12 +08:00
    lzdhlsc
        1
    lzdhlsc  
       Nov 2, 2021
    如果没理解错的话,这段代码逻辑上好像没什么问题。只需要在 `if ... elif ...` 后面加一个 `else` 然后 `raise` exception 来处理 `query_type` 其他的情况就好了。
    Dragonish3600
        2
    Dragonish3600  
       Nov 2, 2021
    代码看上去没大问题
    其实可以把 2 个 return 放到 if elif 外面
    harryhao
        3
    harryhao  
       Nov 2, 2021   ❤️ 1
    在函数开头声明 max_result 变量,比如 max_result = None
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5082 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 01:10 · PVG 09:10 · LAX 18:10 · JFK 21:10
    ♥ Do have faith in what you're doing.