Capture and profitability in understanding the list

I am writing a generator function. I want to find out if there is a better way (read: more pythonic, ideally with a list) a way to implement something like this:

generator = gen() captures = [] for _ in xrange(x): foo = next(generator) directories.append(foo['name']) yield foo 

The key point here is that I don't want to get the WHOLE result - the dictionary returned by gen() is large, so I use a generator. However, I need to capture all the "names". I feel that there is a way to do this with a list, but I just don't see it. Thoughts?

+4
source share
2 answers

There is another / shorter way to do this, but I would not call it more Pythonic:

 generator = gen() directories = [] generator_wrapper = (directories.append(foo['name']) or foo for foo in generator) 

This exploits the fact that append , like all mutating methods in Python, always returns None , so .append(...) or foo will always evaluate foo .

So the whole dictionary is still the result of a generator expression, and you still get a lazy rating, but the name is still stored in the directories list.

You can also use this method in an explicit for loop:

 for foo in generator: yield directories.append(foo['name']) or foo 

or even simplify the loop a bit:

 for foo in generator: directories.append(foo['name']) yield foo 

since there is no reason to use xrange only to iterate over the generator (unless you really want to just repeat a number of known steps).

+6
source

Do you want the first x many generator elements? Use itertools.islice :

 directories = [item['name'] for item in itertools.islice(gen(), x)] 
0
source

Source: https://habr.com/ru/post/1436896/


All Articles