gpt4 book ai didi

Python - 简单的 for 循环没有按预期工作(使用请求模块)

转载 作者:行者123 更新时间:2023-11-28 22:16:45 24 4
gpt4 key购买 nike

我一定是遗漏了一些东西,因为计算机不会开玩笑,但这个简单的 for 循环似乎没有给我想要的输出。下面是使用 aztro's API 的代码获取 12 个星座中每个星座的今日星座运势,并将它们全部放入一个列表中。

import requests
import json

zodiacSigns = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces']

for zodiacSign in zodiacSigns:
params = (('sign','{}'.format(zodiacSign)), ('day','today'))
output = json.loads(requests.post('https://aztro.sameerkumar.website/', params=params).text)
descriptions = []
descriptions.append(output['description'])

print(descriptions)

此代码仅输出双鱼座的星座,即上面列表中的最后一个元素:

["You need to take work more seriously today -- it may be that you've got an opportunity coming up that shouldn't be missed. It's easier than usual for you to make career moves, so go for it!"]

作为引用,此 aztro 的单个星座 API 的示例输出是:

{
"compatibility":" Virgo",
"date_range":"Jan 20 - Feb 18",
"current_date":"August 23, 2018",
"description":"Today requires a willingness to go deeper than usual -- maybe to explore the nuances of your primary relationship, maybe to really get to know that one client or maybe just reading between the lines.",
"lucky_time":" 10am",
"lucky_number":" 13",
"color":" Navy Blue",
"mood":" Thoughtful"
}

所需的输出将是所有 12 个星座的星座列表。我似乎无法在这里解决问题,所以我很感激更有经验的人的意见。谢谢!

最佳答案

问题在于 descriptions 变量的声明,它在每次迭代时都被初始化为一个空列表。

只需将它从循环中移出,如下所示:

descriptions = []
for zodiacSign in zodiacSigns:
params = (('sign','{}'.format(zodiacSign)), ('day','today'))
output = json.loads(requests.post('https://aztro.sameerkumar.website/', params=params).text)
descriptions.append(output['description'])

关于Python - 简单的 for 循环没有按预期工作(使用请求模块),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992959/

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