【问题标题】:Python append array to array in loop [duplicate]Python将数组追加到循环中的数组[重复]
【发布时间】:2020-09-21 08:22:17
【问题描述】:

我是从 PHP 到 python。

在 PHP 中我这样做:

$result = array();

foreach($videos as $video) {
  $result[] = array("title"=>$video->title,"description"=>$video->title);
}

print_r($result);

现在,当我在 python 烧瓶中尝试此操作时,我收到错误 很抱歉,但出了点问题:无法启动 Web 应用程序

result = {}

for video in videos:
    title = video['title']
    description = video['description']
    content = {'title':title, 'description': description}
    result[] = content

我该如何解决?

这里是完整的功能

@app.route("/add_channel", methods=['POST'])
def add_channel():
    if request.method == "POST":
        id=request.form['channel']
        videos = get_channel_videos(id)

         result = []
         for video in videos:
             result.append({'id': video['id'], 'title': video['snippet']['title']})
    return result

【问题讨论】:

    标签: python


    【解决方案1】:

    如果您的最终结果是字典列表,那么最后一行将是

    result.append(content)
    

    更简洁地可以在列表理解中实现

    result = [{'title': video['title'], 'description': video['description']} for video in videos]
    

    【讨论】:

    • 试过 result.append(content) 并得到这个错误 AttributeError: 'dict' object has no attribute 'append'
    • 只需将 result = {} 改为 result = [],result = {} 声明一个字典
    • 您将在循环之前使用列表初始化 result = [] 否则 {} 创建字典
    • 仍然报错** TypeError:视图函数没有返回有效响应。返回类型必须是字符串、字典、元组、响应实例或 WSGI 可调用,但它是一个列表。**
    • 我已经尝试了所有建议,但当我返回结果时仍然出现错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2014-11-03
    相关资源
    最近更新 更多