【问题标题】:Concatenating FOR loop output连接 FOR 循环输出
【发布时间】:2018-08-06 16:53:31
【问题描述】:

我对 Python 非常陌生(积极使用的第一周)。我有一些 bash 脚本编写经验,但决定学习 Python。

我有一个包含多个字符串的变量,用于在 FOR 循环中构建 URL。 URL 的输出是 JSON,我想将完整的输出连接到一个文件中。

出于隐私原因,我会放随机 URL。

代码如下所示:

==================

numbers = ['24246', '83367', '37643', '24245', '24241', '77968', '63157', '76004', '71665']

for id in numbers:
        restAPI = s.get(urljoin(baseurl, '/test/' + id + '&test2'))

result = restAPI.json

==================

问题是,如果我这样做 print(result),我只会得到最后一次迭代的输出,即 www.google.com/test/71665&test2

通过添加 text = [] 创建列表有效(内容已连接),但我想保留原始格式。

text = []

for id in numbers:

        restAPI = s.get(urljoin(baseurl, '/test/' + id + '&test2'))

有人知道怎么做吗

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案1】:

    for 循环结束时,for 循环内分配的变量只保留最后一个值。 IE。每次您的代码 for 循环通过时,restAPI 变量每次都会重置。

    如果你想保留每个 URL,你可以 append 每次都在 for 循环范围之外的列表中,即

    restAPI = s.get(urljoin(baseurl, ...
    url_list.append(restApi.json)
    

    或者如果您只是想打印...

    for id in numbers:
        restAPI = s.get(urljoin(baseurl, ...
        print(restAPI.json)
    

    如果您将它们添加到列表中,您可以使用新的 URL 列表执行单独的功能。

    如果您认为可能存在重复,请随意使用set()(它会在添加新值时自动删除可迭代对象中的重复项)。你可以使用set_name.add(restAPI.json)

    为了更好,您可以实现 dict 并将 id 作为键和 json 对象作为值。所以你可以:

    dict_obj = dict()
    
    for id in numbers:
        restAPI = s.get(urljoin(baseurl, ...
        dict_obj[id] = restAPI.json
    

    这样您可以稍后在脚本中查询字典。

    请注意,如果您要查询多个 URL,则将 JSON 存储在内存中可能会占用大量资源,具体取决于您的硬件。

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 2019-08-12
      • 2019-04-14
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多