繁体   English   中英

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

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

我正在尝试在 Python 中“减去” function ,它将接受任意数量的数字并减去它们。 我尝试使用 Numpy 的“减法”function,但出现错误消息:

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, 2, 1)
1

subtract(100, 6)
94

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM