您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页python元组乘,Python将等长的元组相乘

python元组乘,Python将等长的元组相乘

来源:五一七教育网

I was hoping for an elegant or effective way to multiply sequences of integers (or floats).

My first thought was to try (1, 2, 3) * (1, 2, 2) would result (1, 4, 6), the products of the individual multiplications.

Though python isn't preset to do that for sequences. Which is fine, I wouldn't really expect it to. So what's the pythonic way to multiply (or possibly other arithmetic operations as well) each item in two series with and to their respective indices?

A second example (0.6, 3.5) * (4, 4) = (2.4, 14)

解决方案

The simplest way is to use zip function, with a generator expression, like this

tuple(l * r for l, r in zip(left, right))

For example,

>>> tuple(l * r for l, r in zip((1, 2, 3), (1, 2, 3)))

(1, 4, 9)

>>> tuple(l * r for l, r in zip((0.6, 3.5), (4, 4)))

(2.4, 14.0)

In Python 2.x, zip returns a list of tuples. If you want to avoid creating the temporary list, you can use itertools.izip, like this

>>> from itertools import izip

>>> tuple(l * r for l, r in izip((1, 2, 3), (1, 2, 3)))

(1, 4, 9)

>>> tuple(l * r for l, r in izip((0.6, 3.5), (4, 4)))

(2.4, 14.0)

You can read more about the differences between zip and itertools.izip in this question.

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务