两个列表相乘python_用python生成两个列表上的乘积之和?

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))

也可以节省内存。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值