简体   繁体   English

使用生成器从列表理解中生成列表

[英]Make list out of list comprehension using generator

I've been trying to turn the output of my list comprehension into a variable.我一直在尝试将列表理解的输出转换为变量。 Quite silly, but no matter what I try, I seem to end up with an empty list (or NoneType variable).很愚蠢,但无论我尝试什么,我似乎最终都会得到一个空列表(或 NoneType 变量)。

I'm guessing it has something to do with the generator that it uses, but I'm not sure how to get around it as I need the generator to retrieve the desired results from my JSON file.我猜它与它使用的生成器有关,但我不确定如何解决它,因为我需要生成器从我的 JSON 文件中检索所需的结果。 (And I'm too much of a list comprehension and generator newbie to see how). (而且我对列表理解和生成器新手太多了,无法了解如何)。

This is the working piece of code (originally posted as an answer to these questions ( here and here )).这是工作代码(最初发布为这些问题的答案( 此处此处))。

I'd like the output of the print() part to be written to a list.我希望将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])

Any help would be greatly appreciated!任何帮助将不胜感激!

A generator keeps its state, so after you iterate through it once (in order to print), another iteration will start at the end and yield nothing.生成器保持其状态,因此在您迭代一次(为了打印)之后,另一次迭代将在最后开始并且不产生任何结果。

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

Instead, do this:相反,请执行以下操作:

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM