In [159]: import sympy as sy
In [160]: from sympy.abc import x
In [161]: terms = [1, x, x*(x-1)]
In [162]: coefficients = [-1,8.1,7]
In [163]: sum(t*c for t, c in zip(terms, coefficients))
Out[163]: 7*x*(x - 1) + 8.1*x - 1
有趣的是,sum(term*coef for term, coef in zip(terms, coefficients))比sum(coef * term for coef, term in zip(coefficients, terms))快一点:
^{pr2}$
这是因为coef * term调用coef.__mul__(term),后者必须调用term.__rmul__(coef),因为int不知道如何与sympy符号相乘。这个额外的函数调用使coef * term比term * coef慢。(term * coef直接调用term.__mul__(coef)。)
以下是更多的微基准:In [178]: %timeit sum(IT.imap(op.mul, coefficients, terms))
10000 loops, best of 3: 38 µs per loop
In [186]: %timeit sum(IT.imap(op.mul, terms, coefficients))
10000 loops, best of 3: 32.8 µs per loop
In [179]: %timeit sum(map(op.mul, coefficients, terms))
10000 loops, best of 3: 38.5 µs per loop
In [188]: %timeit sum(map(op.mul, terms, coefficients))
10000 loops, best of 3: 33.3 µs per loop
请注意,terms和{}的顺序很重要,但是在其他方面,这些变体之间几乎没有时间差。对于较大的输入,它们的性能也大致相同:In [203]: terms = [1, x, x*(x-1)] * 100000
In [204]: coefficients = [-1,8.1,7] * 100000
In [205]: %timeit sum(IT.imap(op.mul, terms, coefficients))
1 loops, best of 3: 3.63 s per loop
In [206]: %timeit sum(term * coef for term, coef in zip(terms, coefficients))
1 loops, best of 3: 3.63 s per loop
In [207]: %timeit sum(map(op.mul, terms, coefficients))
1 loops, best of 3: 3.48 s per loop
还要注意,如果您不知道(通过分析)此操作是代码中的一个关键瓶颈,那么担心这些细微的差异是在浪费时间,因为预优化这些内容所需的时间远远大于代码运行时节省的时间。就像他们说的,preoptimization is the root of all evil。我可能已经为此感到内疚了。在
在Python2中sum(IT.imap(op.mul, coefficients, terms))
使用最少的内存。在
在Python3中,zip和{}返回迭代器,因此sum(t*c for t, c in zip(terms, coefficients))
sum(map(op.mul, coefficients, terms))
也可以节省内存。在