【问题标题】:filter python requests result过滤python请求结果
【发布时间】:2021-04-19 10:15:53
【问题描述】:

我是 Python 新手,正在使用请求从 API 中提取数据,现在我只想对输出中的某些值求和:

import requests
import json

url = "APIlink"

payload={}
headers = {
  'Authorization': 'Bearer '+accesstoken
}
response = requests.request("GET", url, headers=headers, data=payload)
output = response.json()

当我打印输出时,我得到如下所示的结果:

[{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}]

如何仅过滤容量? 我怎样才能将所有容量加起来为 36?

我尝试了类似 print(output[0].capacity) 的方法来测试我将如何执行此操作,但随后我得到以下结果:

AttributeError: 'dict' 对象没有属性 'capacity' 这是否意味着它仍然没有 JSON 输出?

我可能错过了一些非常基本的东西......

【问题讨论】:

  • 您需要了解收到的响应类型。输出是一个包含 Python 字典的 Python 列表。你可以访问像 output[0]['capacity'] 这样的容量。

标签: python filter output


【解决方案1】:

从 API 获取数据后,您可以做任何您想做的事情。

例如,您可以使用列表推导对容量求和。

capacity = sum([x['capacity'] for x in output])

或者像这样过滤

filtered =  list(filter(lambda x: x['id'] ==1, output))

注意,你的输出中有列表。

【讨论】:

    【解决方案2】:
    json = [{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}]
    
    print(json[0]["capacity"])
    

    字典有键,你可以在方括号中引用它们!(["capacity"])另外,这是一个列表,所以你必须写[0]来获取列表的元素。

    【讨论】:

      【解决方案3】:

      您有一个字典列表。在其他解决方案中,您可以使用

      result = sum([x['capacity'] for x in output])
      

      【讨论】:

        【解决方案4】:

        字典键使用[] 进行索引,例如:

        foo = {"bar": 69}
        print(foo["bar"])
        

        将打印数字 69

        在您的情况下,通过理解快速简单地总结所有能力:

        output = [{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}
        
        total = sum(dictionary["capacity"] for dictionary in output)
        

        总共是 36 个

        旁注/提示,使用 dict.get() 而不是 dict[] 宁可返回 None 而不是索引错误,例如:

        # This will throw a KeyError
        dictionary = {"foo": 69}
        x = dictionary["baz"]
        
        # This will return None
        x = dictionary.get("baz")
        

        【讨论】:

          【解决方案5】:

          这是一个字典列表。 item 是一个带有键值对的字典。

          my_dict = [{'id': 1, 'capacity': 5}, {'id': 2, 'capacity': 31}]
          for item in my_dict:
              print(item['capacity'])
          

          输出:

          5,31
          

          【讨论】:

            猜你喜欢
            • 2019-03-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-04-14
            • 2022-06-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多