温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to print only the max value of an ouput
max printing python python-requests set

python - 如何仅打印输出的最大值

发布于 2020-04-14 16:16:09

我见过很多关于该主题的帖子,但没有一个对我有用。因此,我要问自己关于我要做什么的问题。我设置的代码如下。

def get_assets_for_group(ip):
    decom_match = str(ip)
    url5 = server + path1
    response = requests.request("GET", url5, headers=headers, verify=False)
    data = response.json()
    for i in data['resources']: 
        url = server+path2+str(i)
        response = requests.request("GET", url, headers=headers, verify=False)
        data = response.json()
        if decom_match in data["ip"]:
            d = {i}
            max_value = max(d)
            print("Match found!", max_value)

当我只希望它返回最大数字时,此代码的输出将为我提供所有匹配的值。输出示例如下。

Match found! 111618
Match found! 112367
Match found! 115401
Match found! 115618
Match found! 116265
Match found! 116400
Match found! 117653

我使用max函数错误吗?请让我知道您的想法或可能的解决方法。

查看更多

提问者
pythonscrub
被浏览
42
CDJB 2020-02-03 22:51

问题是,每次找到匹配值时,您都将max()函数应用到仅包含i-然后打印结果的集合上纠正此问题的一种方法是创建一个初始集合,matches然后每次找到匹配项时,将其添加到该集合中。在搜索响应中找到匹配项后,可以max()在此集合上使用并打印结果。

像这样:

def get_assets_for_group(ip):
    decom_match = str(ip)
    url5 = server + path1
    response = requests.request("GET", url5, headers=headers, verify=False)
    data = response.json()

    matches = set()

    for i in data['resources']: 
        url = server+path2+str(i)
        response = requests.request("GET", url, headers=headers, verify=False)
        data = response.json()
        if decom_match in data["ip"]:
            matches.add(i)

    if matches:
        print("Match found!", max(matches))