gpt4 book ai didi

python - 将从 REST api 检索到的数据存储到 python 中的变量中

转载 作者:行者123 更新时间:2023-11-30 23:19:41 27 4
gpt4 key购买 nike

因此,我尝试更多地了解 API 以及使用它们的不同方式。说到现在为止我已经

import requests, json, pprint

r = requests.get("values from api")

pprint.pprint(r.json())

它返回给我以下内容

> {'currentResultCount': '10',  
> 'results': [{'Name': 'Item_One',
> 'Price': '464086'},
> {'Name': 'Item_Two',
> 'Price': '70874',
> and so on.........

如果我想将所有价格存储在一个数组中并对它们进行一些数据分析(例如求平均值、中位数和众数),我应该怎么做?

我尝试调用 r[0] 来查看它是否有效,但显然 r 是响应对象类型,因此 r[0] 不起作用。这是我第一次学习 API 和数据操作,非常感谢任何建议和学习技巧!

最佳答案

.json()在底层解析 JSON 响应并返回一个 Python 数据结构,在您的例子中,是一个常规的 dictionary :

data = r.json()

要获取价格列表,请迭代结果值并在每次迭代时获取价格:

prices = [item['Price'] for item in data['results']]

您还可以将价格定为 float :

prices = [float(item['Price']) for item in data['results']]

关于python - 将从 REST api 检索到的数据存储到 python 中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25943063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com