【问题标题】:Make list out of list comprehension using generator使用生成器使列表脱离列表理解
【发布时间】:2020-07-13 07:02:45
【问题描述】:

我一直在尝试将列表理解的输出转换为变量。很傻,但无论我尝试什么,我似乎最终都会得到一个空列表(或 NoneType 变量)。

我猜它与它使用的生成器有关,但我不确定如何绕过它,因为我需要生成器从我的 JSON 文件中检索所需的结果。 (而且我是一个列表理解和生成器新手,不知道怎么做)。

这是工作代码(最初发布为这些问题的答案(herehere))。

我希望将print() 部分的输出写入列表。

def item_generator(json_Response_GT, identifier):
    if isinstance(json_Response_GT, dict):
        for k, v in json_Response_GT.items():
            if k == identifier:
                yield v
            else:
                yield from item_generator(v, identifier)
    elif isinstance(json_Response_GT, list):
        for item in json_Response_GT:
            yield from item_generator(item, identifier) 

res = item_generator(json_Response_GT, "identifier")
print([x for x in res])

任何帮助将不胜感激!

【问题讨论】:

    标签: python list generator list-comprehension q


    【解决方案1】:

    生成器保持其状态,因此在您迭代一次(为了打印)之后,另一次迭代将在最后开始并且什么也不产生。

    print([x for x in res]) # res is used up here
    a = [x for x in res] # nothing left in res
    

    相反,这样做:

    a = [x for x in res] # or a = list(res)
    # now res is used up, but a is a fixed list - it can be read and accessed as many times as you want without changing its state
    print(a)
    

    【讨论】:

    • 感谢您的解释!颠倒顺序确实起到了作用。 (:
    【解决方案2】:

    res = [x for x in item_generator(json_Response_GT, "identifier")] 应该可以解决问题。

    【讨论】:

    • 现在感觉好傻哈哈。应该能够自己想出这个。谢谢!
    猜你喜欢
    • 2019-10-12
    • 2023-01-26
    • 2013-12-30
    • 2021-04-07
    • 2016-10-04
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    相关资源
    最近更新 更多