【问题标题】:How to return a list with a certain parameter from an API?如何从 API 返回带有特定参数的列表?
【发布时间】:2022-11-23 23:41:27
【问题描述】:

我需要返回一个列表,其中包含出现在这个 api 中的新闻的标题(“titulo”):https://www.publico.pt/api/list/ultimas

我试过了,但它只返回第一个新标题的标题 (titulo),而不是所有标题。

import requests

def get_news():
    
    url = "https://www.publico.pt/api/list/ultimas"

    response = requests.get(url)
    data = response.json()  
    for news in data:
        titulo = [news["titulo"]]  
        
        return titulo
    
print(get_news())

【问题讨论】:

  • 将 for 循环替换为 return [news["titulo"] for news in data]

标签: python list api


【解决方案1】:

我想这可能是你真正想做的:

url = "https://www.publico.pt/api/list/ultimas"

response = requests.get(url)
data = response.json()
titulo = []
for news in data:    
    titulo.append(news["titulo"])  
    
return titulo

这会将所有数据放入列表并返回列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2013-10-30
    相关资源
    最近更新 更多