Python-简单的for循环未按预期运行(带有请求模块)

时间:2018-08-23 19:25:10

标签: python api for-loop python-requests append

由于计算机没有在开玩笑,所以我在这里一定会缺少一些东西,但是这种简单的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个十二生肖的星座运势列表。我似乎无法在这里解决问题,因此,我感谢有经验的人的意见。格拉西亚斯!

2 个答案:

答案 0 :(得分:3)

问题出在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'])

答案 1 :(得分:0)

语句descriptions = []应该在for循环之外。如果它在for循环中,则它将在每次迭代时启动(在这种情况下,将其擦除)。

下面的代码应该可以工作:

import requests
import json

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

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'])

print(descriptions)