[英]Lambda / List Comprehension for addition
我正在做一個個人項目-python中的一個簡單的基本計算器。 我設法使它主要啟動並運行,但是我還有很多工作要做。 我正在研究分離函數,以便可以在編程意義上正確地調用它們...現在,我想使用lambda或列表理解來簡化加,減,乘和除運算。
這就是我想要做的...
def add(self):
nsum = 0.0
print ("This is addition\n\n")
#Using FOR loop, requests the quantity_of_numbers value of numbers to perform addition
nsum += x for x in self.nVar1
self.print_answer(nSum)
#Resets the variables
self.nVar1 = []
nsum = 0.0
return 0
我不斷收到類似的錯誤消息
TypeError: unsupported operand type(s) for +=: 'float' and 'generator'
logout
如果您想使用lambda和列表理解來做到這一點,那么您需要的是reduce
。
nsum += reduce(lambda x,y: x+y, self.nVar1)
正如其他人所指出的那樣,python具有內置的sum
函數,我認為實際上並不是以這種方式實現的,而是ac函數的包裝器。
由於某些原因,reduce已從Python 3中的適當語言中刪除。如果import functools
它仍然可用。
例外情況:
TypeError: unsupported operand type(s) for +=: 'float' and 'generator'
對此抱怨:
nsum += x for x in self.nVar1
您要在其中添加浮點數( nsum
)和生成器的地方( x for x in self.nVar1
)
您可以嘗試以下方法:
nsum += sum(self.nVar1)
其中sum
函數通過將self.nVar1
序列加在一起並給出結果來將其減少為一個數。
x for x in self.nVar1
是生成器表達式-它返回生成器,您嘗試將其添加到nsum
,從而導致錯誤。
根據您要實現正確解決方案的目的,可能使用內置的python sum
nsum = sum(self.nVar1)
您的for循環語法不正確,這就是為什么您收到該錯誤消息的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.