【问题标题】:Get the (multiplicative) product of a tuple or list?获取元组或列表的(乘法)乘积?
【发布时间】:2011-12-13 07:14:25
【问题描述】:

假设我有一个

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(),但仅用于乘法?

感谢大家的帮助。

【问题讨论】:

  • FWIW,您也可以将“* 2”排除在总和之外。
  • 好电话。我改了。

标签: python standard-library


【解决方案1】:

我认为在这里使用索引没有任何问题:

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

【讨论】:

  • 从 python 3.0+ 开始,reduce 不再存在
  • +1 并回答reduce(mul, l) 提示。我同意,初稿更清晰,我只是在寻找一个衬里来扩展我的列表理解......理解。 :D
  • @Serdalis:正确,感谢您的提示。但是有functools.reduce,其实是一样的。
【解决方案2】:

由于这是在 Google 搜索结果中排名靠前的,我将添加从 Python 3.8 开始,您可以这样做:

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

【讨论】:

  • 尽管这实际上并没有回答我的问题,但它与标题相匹配,并且应该是在快速搜索中最容易找到的。不过,为了完全准确,我想将这些产品结果汇总在一起:sum(map(math.prod, itertools.combinations([l, w, h], 2))) * 2
  • 哈哈感谢9年后维护这个问题!稍短的版本:2*(h*w+h*l+l*w)itertools.combinations 确实对更高维度有用,但 math.prod 似乎没有多大帮助。
【解决方案3】:

简而言之,只需使用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 可以同时接受列表和元组作为参数。它返回您想要的产品。

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 请花时间更新这个有效的答案。 “np”显然不起作用 - 这涉及 a)numpy 的导入(根本没有提到)和 2)将此导入别名为 np.我不明白为什么人们会花时间回答问题,但结果却如此糟糕。
【解决方案4】:

你可以这样做:

from operator import mul
sum(reduce(mul,combinations(args, 2)))

但我认为它只会让事情变得不那么可读。

但是,在求和之前,您实际上是在构建乘法列表sum([...])

self.a = sum([(x[0] * x[1] * 2) for x in combinations(args, 2)])

这不是必需的,只需这样做:

self.a = sum(x * y * 2 for x,y in combinations(args, 2))

【讨论】:

  • 我在你的两个例子中都看到了太多的左括号。我在 2.6 中运行我的代码,它为我编译。不过,我会试试for x, y in 位。
  • 我修正了我的错字,你应该修正你的:) 这里有问题sum(([x[0]...
  • 为什么不为像我这样的菜鸟配备口译员?好眼力。
  • @Ugo: (x[0] * x[1] * 2) 不是元组。与x[0] * x[1] * 2 相同。您需要输入 , 以制作长度为 1 的元组,例如(2,).
【解决方案5】:

我确实对产品做了一个非常简单的定义;有助于“计算元组的乘积”

def product(tuple1):
    """Calculates the product of a tuple"""
    prod = 1
    for x in tuple1:
        prod = prod * x
    return prod

可能是一种更优雅的方式,但这似乎工作正常。大概它也适用于列表。

【讨论】:

    猜你喜欢
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多