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

How can I subtract all given numbers in function with *args in python?

我正在尝试在 Python 中创建一个 'subtract' 函数,它将接受任意数量的数字并将它们相减。我尝试使用 Numpy 的 'subtract' 函数,但我收到一条错误消息:

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

版本信息:

Python3.9.4(Python版本)

macOS BigSur 11.3(Os 版本)

PyCharm CE 2021.1(代码编辑器)

您可以使用 functools.reduce 搭配 operator.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, 2, 1)
1

subtract(100, 6)
94