list slice and generators
Ian Kelly
ian.g.kelly at gmail.com
Wed Nov 25 12:44:35 EST 2015
On Wed, Nov 25, 2015 at 3:07 AM, Peter Otten <__peter__ at web.de> wrote:
> to get down to one intermediate list. Avoiding the last one is a bit tricky:
>
> metrics = (converter(x.metric(name)) for x in self._server_per_proc)
> metrics = (x for x in metrics if x is not None)
> try:
> # if there is at least one item the generator is not empty
> first = next(metrics)
> except StopIteration:
> metrics = ()
> else:
> # put the first item back in
> metrics = itertools.chain([first], metrics)
> assert metrics
metrics is always going to be an itertools.chain object at this
assert, so how could the assertion ever fail?
>> elif name in METRICS_AVG:
> # writing a function that calculates the average without
> # materialising the list left as an exercise ;)
metrics = itertools.tee(metrics)
return int(sum(metrics[0]) / len(metrics[1]))
More information about the Python-list
mailing list