本文介紹了什么是類似于 sum() 的減法函數,用于減去列表中的項目?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試創建一個計算器,但我無法編寫一個從列表中減去數字的函數.
例如:
I am trying to create a calculator, but I am having trouble writing a function that will subtract numbers from a list.
For example:
class Calculator(object):
def __init__(self, args):
self.args = args
def subtract_numbers(self, *args):
return ***here is where I need the subtraction function to be****
對于加法,我可以簡單地使用 return sum(args)
來計算總數,但我不確定我可以為減法做什么.
For addition, I can simply use return sum(args)
to calculate the total but I am unsure of what I can do for subtractions.
推薦答案
from functools import reduce # omit on Python 2
import operator
a = [1,2,3,4]
xsum = reduce(operator.__add__, a) # or operator.add
xdif = reduce(operator.__sub__, a) # or operator.sub
print(xsum, xdif)
## 10 -8
reduce(operator.xxx, list)
基本上是在列表元素之間插入"運算符.
reduce(operator.xxx, list)
basically "inserts" the operator in-between list elements.
這篇關于什么是類似于 sum() 的減法函數,用于減去列表中的項目?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!