Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #99413

list slice and generators

From Pavlos Parissis <pavlos.parissis@gmail.com>
Newsgroups comp.lang.python
Subject list slice and generators
Date 2015-11-24 22:38 +0100
Message-ID <mailman.50.1448431814.20593.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

Hi,

Do you see any possible dangerous hidden bug in the below code(using
python2.7 and python3.4)?

My goal is to avoid go through the metrics list twice. But, I don't
know if there will be a problem with doing in place replace of list
elements using 2 generators.

# metrics = ['', '0', '10'....]
metrics = [x.metric(name) for x in self._server_per_proc]
metrics[:] = (converter(x) for x in metrics)
metrics[:] = (x for x in metrics if x is not None)

return calculate(name, metrics)


def calculate(name, metrics):
     if not metrics:
        return None

    if name in METRICS_SUM:
        return sum(metrics)
    elif name in METRICS_AVG:
        return int(sum(metrics)/len(metrics))
    else:
        raise ValueError("Unknown type of calculation for {}".format(name))


def converter(value):
    try:
        return int(float(value))
    except ValueError:
        return value.strip() or None
    except TypeError:
        return None


Cheers,
Pavlos

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

list slice and generators Pavlos Parissis <pavlos.parissis@gmail.com> - 2015-11-24 22:38 +0100

csiph-web