Domanda

#L is a very large list
A = [x/sum(L) for x in L]

When the interpreter evaluates this, how many times will sum(L) be calculated? Just once, or once for each element?

È stato utile?

Soluzione

A list comprehension executes the expression for each iteration.

sum(L) is executed for each x in L. Calculate it once outside the list comprehension:

s = sum(L)
A = [x/s for x in L]

Python has no way of knowing that the outcome of sum(L) is stable, and cannot optimize the call away for you.

sum() could be rebound to a different function that returns random values. The elements in L could implement __add__ methods that produce side effects; the built-in sum() would be calling these. L itself could implement a custom __iter__ method that alters the list in-place as you iterate, affecting both the list comprehension and the sum() call. Any of those hooks could rebind sum or give x elements a __div__ method that alters sum, etc.

In other words, Python is too dynamic to accurately predict expression outcomes.

Altri suggerimenti

I would opt for Martijn's approach, but thought I'd point out that you can (ab)use a lambda with a default argument and a map if you wanted to retain a "one-liner", eg:

L = range(1, 10)
A = map(lambda el, total=sum(L, 0.0): el / total, L)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top