为此:
from itertools import izip
def average(items):
total = sum((next - last).seconds + (next - last).days * 86400
for next, last in izip(items[1:], items))
return total / (len(items) - 1)
我认为,这样做更可读。 对较不以数学为名的读者发表评论可能有助于解释你是如何计算每一三角洲的。 对于其价值而言,一个发电机的表述对我所研究的任何内容至少(而且我认为至少是缓慢的)不成像指示。
# The way in your question compiles to....
3 0 LOAD_CONST 1 (<code object <lambda> at 0xb7760ec0, file
"scratch.py", line 3>)
3 MAKE_FUNCTION 0
6 STORE_DEREF 1 (delta)
4 9 LOAD_GLOBAL 0 (sum)
12 LOAD_CLOSURE 0 (items)
15 LOAD_CLOSURE 1 (delta)
18 BUILD_TUPLE 2
21 LOAD_CONST 2 (<code object <genexpr> at 0xb77c0a40, file "scratch.py", line 4>)
24 MAKE_CLOSURE 0
27 LOAD_GLOBAL 1 (range)
30 LOAD_CONST 3 (1)
33 LOAD_GLOBAL 2 (len)
36 LOAD_DEREF 0 (items)
39 CALL_FUNCTION 1
42 CALL_FUNCTION 2
45 GET_ITER
46 CALL_FUNCTION 1
49 CALL_FUNCTION 1
52 STORE_FAST 1 (total)
5 55 LOAD_FAST 1 (total)
58 LOAD_GLOBAL 2 (len)
61 LOAD_DEREF 0 (items)
64 CALL_FUNCTION 1
67 LOAD_CONST 3 (1)
70 BINARY_SUBTRACT
71 BINARY_DIVIDE
72 STORE_FAST 2 (average)
75 LOAD_CONST 0 (None)
78 RETURN_VALUE
None
#
#doing it with just one generator expression and itertools...
4 0 LOAD_GLOBAL 0 (sum)
3 LOAD_CONST 1 (<code object <genexpr> at 0xb777eec0, file "scratch.py", line 4>)
6 MAKE_FUNCTION 0
5 9 LOAD_GLOBAL 1 (izip)
12 LOAD_FAST 0 (items)
15 LOAD_CONST 2 (1)
18 SLICE+1
19 LOAD_FAST 0 (items)
22 CALL_FUNCTION 2
25 GET_ITER
26 CALL_FUNCTION 1
29 CALL_FUNCTION 1
32 STORE_FAST 1 (total)
6 35 LOAD_FAST 1 (total)
38 LOAD_GLOBAL 2 (len)
41 LOAD_FAST 0 (items)
44 CALL_FUNCTION 1
47 LOAD_CONST 2 (1)
50 BINARY_SUBTRACT
51 BINARY_DIVIDE
52 RETURN_VALUE
None
尤其是,放弃“拉姆布达”使我们得以避免关闭、修建图形和装载两条封锁。 有5项职能要么被称之为。 当然,这种对业绩的关切是荒谬的,但很想知道谁在爱护下工作。 最重要的事情是可读性,我认为这样做也是如此。