import json
import requests
def names(threshold):
data = requests.get("https://example.com/users/search?page={}")
response = json.loads(data.content.decode('utf-8'))
#print(response)
for page in range(0, response["total_pages"]):
page_r = requests.get("https://example.com/users/search?page={}".format(page + 1))
page_con = json.loads(page_response.content.decode('utf-8'))
#print(page_con)
for i in page_con["data"]:
if i["bottles"] > threshold:
return(i["name"])
print(names(10))
打印错误:
norman
我所期望的是:
norman
oliver
Kyle
Zaaz
Chris
Jordan
Richard
Dora
Paul
Lena
在json中,我已经有15个名字了 P.S.2如果我将打印(I[“名称”])而不是返回(I[“名称”]),那么我将获得完整列表,但没有:
norman
oliver
Kyle
Zaaz
Chris
Jordan
Richard
Dora
Paul
Lena
None
我怎样才能修好它?请帮忙
根据我所知(这是非常小的,因为您正在使用的url失败),您正在尝试索引到“Json”(您不是),并且您正在尝试将它的后续值与阈值变量的值进行比较
loads将返回python语言可以表示的数据结构,通常以列表、字典或字典列表的形式出现,以此类推。但是,您并没有在代码中检查这些内容,您只是试图从url获取数据结构,并在其中任意循环。因为您的代码没有运行,所以我使用jsonplaceholder api尝试重新创建您的问题
目前,您的代码中还存在一些其他问题,我想我最好解释并解决这些问题。尽我所能
python语言有一种称为“类型提示”的东西,它允许您建议变量的类型,或者函数返回的类型。与C++和其他静态类型语言不同,Python类型的提示仅仅是建议而不是命令。但它有助于代码的可读性,并在尝试遍历数据结构时对您有所帮助。遍历列表和字典是完全不同的事情。毕竟你不能处理数据,除非你知道数据的结构
您的比较在逻辑上是错误的,它不会过滤掉任何值, 另外,如果“i”的这个特定迭代没有一个名为“瓶子”的键,那么代码就会崩溃
最好只写一行:
相关问题 更多 >
编程相关推荐