如何在python中用* args减去函数中的所有给定数字?

问题描述

我正在尝试在 Python 中创建一个“减法”函数,它可以接收任意数量的数字并将它们相减。我尝试使用 Numpy 的“减法”函数,但出现错误

Traceback (most recent call last):
  File "/Users/myname/Desktop/Python/Calculator/calculator_test.py",line 27,in <module>
    print(subtract(100,6))  # Should return 94
  File "/Users/myname/Desktop/Python/Calculaotr/calculator_test.py",line 14,in subtract
    return np.subtract(numbers)  # - This isn't working
ValueError: invalid number of arguments

我的代码

from math import prod
import numpy as np


# Simple calculator app

# Add function
def add(*numbers):
    return sum(numbers)


# Subtract function
def subtract(*numbers):
    return np.subtract(numbers)  # - This isn't working


# Multiply function
def multiply(*numbers):
    return prod(numbers)


# Divide function
def divide(*numbers):
    return


print(subtract(100,6))  # Should return 94

版本信息:

Python 3.9.4(Python 版本)

macOS BigSur 11.3(操作系统版)

PyCharm CE 2021.1(代码编辑器)

解决方法

您可以将 functools.reduceoperator.sub 配对用于减法或与 operator.truediv 配对用于除法:

from operator import sub,truediv
from functools import reduce


def divide(*numbers):
    return reduce(truediv,numbers)


def subtract(*numbers):
    return reduce(sub,numbers)

divide(4,2,1)
2.0

subtract(4,1)
1

subtract(100,6)
94