my for循环在每次迭代中提取一个词典列表。我试图用我在每次迭代中得到的所有列表扩展final_list。但是最后,当我打印final_list时,只是给了我上次迭代的列表。换句话说,它几乎像以前的所有列表一样被覆盖。尝试了一切,但无济于事。有人可以指出我的代码有什么问题吗?
for i in range (1,21):
results_list = []
final_list = []
url = "https://api.themoviedb.org/3/discover/movie?api_key=XX&primary_release_date.gte=2000-01-01&with_genres=35&sort_by=popularity.desc&page=" + str(i)
response = requests.get(url, timeout = 10)
#each page is a dictionary. we get only "results" which is a list.
#so each iteration of the loop gives us a list to work with
results_list = response.json()['results']
final_list.extend(results_list)
if response.status_code != 200:
print('Failed to get data:', response.status_code)
print(final_list)
答案 0 :(得分:0)
您的代码中有两次result_list,一次是可以的空列表,第二次是一个对象。您不是通过以下方式更新列表:
results_list = response.json()['results']
您正在将其另存为覆盖空列表的对象。而是将每个值存储在名为“ results”的变量中,然后将其附加到列表“ results_list”
尝试以下操作:
results_list = []
for i in range (1,21):
url = "https://api.themoviedb.org/3/discover/movie?api_key=XX&primary_release_date.gte=2000-01-01&with_genres=35&sort_by=popularity.desc&page=" + str(i)
response = requests.get(url, timeout = 10)
#each page is a dictionary. we get only "results" which is a list.
#so each iteration of the loop gives us a list to work with
results = response.json()['results']
results_list.append(results)
final_list.extend(results_list)
if response.status_code != 200:
print('Failed to get data:', response.status_code)
print(results_list)