如何获得元组或列表的乘积?

14 投票
5 回答
25779 浏览
提问于 2025-04-17 04:49

假设我有一个

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() 一样,但只用来做乘法的呢?

谢谢大家的帮助。

5 个回答

6

简单来说,就是用 np.prod

import numpy as np
my_tuple = (2, 3, 10)
print(np.prod(my_tuple))  # 60

在你的这个情况中,

np.sum(np.prod(x) for x in combinations(args, 2))

np.prod 可以接受列表和元组作为参数。它会返回你想要的乘积。

11

我觉得在这里使用索引没有什么问题:

sum([x[0] * x[1] for x in combinations(args, 2)])

如果你真的想避免使用索引,可以这样做:

sum([x*y for x,y in combinations(args, 2)])

不过,说实话,我更喜欢你注释掉的那个版本。它清晰、易读,而且更明确。为了三个变量而把它写成上面的样子,其实并没有太大的好处。

有没有什么函数可以像sum()那样,但只用于乘法呢?

内置的?没有。不过,你可以用下面的代码很简单地实现这个功能:

In : a=[1,2,3,4,5,6]

In : from operator import mul

In : reduce(mul,a)
Out: 720
15

因为这个问题在谷歌搜索结果中排名很高,我就补充一下,自从Python 3.8版本开始,你可以这样做:

from math import prod
t = (5, 10)
l = [2, 100]
prod(t) # 50
prod(l) # 200

撰写回答