【问题标题】:How do I multiply an element's tuple that I got from arg(*arg)? (Python 3)如何乘以从 arg(*arg) 获得的元素元组? (Python 3)
【发布时间】:2021-03-16 15:12:04
【问题描述】:

所以我是 Python 的初学者,我有这个任务。所以,我有一个随机数元组,我的工作是制作一个函数,可以用来将这些数字元组相乘,我的导师建议我使用 args (*args)。

~谢谢~

【问题讨论】:

  • 导入 operatorfunctools 模块。然后:functools.reduce(operator.mul, args)
  • math.prod((1,2,3)) == 6。 (这是 Python 3.8 中的新功能;前几天我自己才知道。)

标签: python arguments tuples multiplication keyword-argument


【解决方案1】:

使用 for 循环:

def prod(args):
    mul = 1
    for x in args:
        mul *= x

    return mul

然后像这样调用:

print(prod((1,2,3))

【讨论】:

  • @chepner 谢谢你拯救了一天,多么愚蠢的错误0*x=0 OMG!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 2021-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多