我一定在这里遗漏了一些东西,因为计算机不会开玩笑,但这个简单的 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/