如何解决如何在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.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,1)
1
subtract(100,6)
94
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。