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

标签 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 个星座的星座运势列表。我似乎无法理解这里的问题,所以我希望有经验丰富的人提供意见。谢谢!

最佳答案

问题在于 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/

相关文章:

python - Py4JException : Constructor org. apache.spark.sql.SparkSession([class org.apache.spark.SparkContext, class java.util.HashMap]) 不存在

python - pandas 使用同一列中的值进行分组并计算结果(包括 R 等效项)

facebook - 使用 Facebook API 可以追溯到多久以前?

python - for循环代码块

javascript - 请帮助我完成这个简单的脚本

javascript - 通过循环读取和插入数据到数组

python - 使用迭代项、上一项和下一项迭代列表时生成新列表

python - 等格式的时区字段

ios - Swift 3 Google Map 和 MapKit API - 如果用户当前位置已更新

php - 无需开发人员/api key 即可从 youtube 获取 Youtube 标题