简体   繁体   中英

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).

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. (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.

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")]应该可以解决问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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