获取元组或列表的(乘法)积?
假设我
class Rectangle(object):
def __init__(self, length, width, height=0):
self.l = length
self.w = width
self.h = height
if not self.h:
self.a = self.l * self.w
else:
from itertools import combinations
args = [self.l, self.w, self.h]
self.a = sum(x*y for x,y in combinations(args, 2)) * 2
# original code:
# (self.l * self.w * 2) + \
# (self.l * self.h * 2) + \
# (self.w * self.h * 2)
self.v = self.l * self.w * self.h
对第 12 行有什么看法?
self.a = sum(x*y for x,y in combinations(args, 2)) * 2
我听说应该避免显式列表索引引用。
是否有一个函数可以使用,其作用类似于 sum()
,但仅用于乘法?< /strike>
感谢大家的帮助。
Let's say I have a
class Rectangle(object):
def __init__(self, length, width, height=0):
self.l = length
self.w = width
self.h = height
if not self.h:
self.a = self.l * self.w
else:
from itertools import combinations
args = [self.l, self.w, self.h]
self.a = sum(x*y for x,y in combinations(args, 2)) * 2
# original code:
# (self.l * self.w * 2) + \
# (self.l * self.h * 2) + \
# (self.w * self.h * 2)
self.v = self.l * self.w * self.h
What's everyone's take on line 12?
self.a = sum(x*y for x,y in combinations(args, 2)) * 2
I've heard that explicit list index references should be avoided.
Is there a function I can use that acts like sum()
, but only for multiplication?
Thanks for the help everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于这是 Google 的顶级结果,我将补充一点,从 Python 3.8 开始,您可以执行以下操作:
Since this is in the top Google results, I'll just add that since Python 3.8, you can do :
我没有看到在这里使用索引有任何问题:
如果你真的想避免它们,你可以这样做:
但是,说实话,我更喜欢你注释掉的版本。它清晰、可读且更明确。仅针对三个变量按照上面的方式编写并不会真正获得太多好处。
内置?不需要。但是您可以通过以下方式简单地获得该功能:
I don't see any problem with using indexes here:
If you really want to avoid them, you can do:
But, to be honest I would prefer your commented out version. It is clear, readable and more explicit. And you don't really gain much by writing it as above just for three variables.
Built-in? No. But you can get that functionality rather simply with the following:
简而言之,只需使用
np.prod
在您的用例中
np.prod
可以将列表和元组作为参数。它会返回您想要的产品。In short, just use
np.prod
Which is in your use case
np.prod
can take both lists and tuple as a parameter. It returns the product you want.你可以这样做:
但我认为这只会让事情变得不那么可读。
但是,在求和之前,您实际上是在构建乘法
sum([...])
列表。这不是必需的,只需执行以下操作:
you can do:
but I think it just makes things less readable.
However, before summing you are actually building the list of multiplication
sum([...])
.This is not needed, simply do:
我确实对产品做了一个非常简单的定义;有助于“计算元组的乘积”
可能是一种更优雅的方法,但这似乎工作正常。想必它也适用于列表。
I did make a very simple definition of product; helpful for "calculating the product of a tuple"
Might be a more elegant way to do it but this seems to work OK. Presumably it would work on a list just as well.