首页 > 解决方案 > 如何在 AWS Lambda 中将浮点值作为输入?

问题描述

我正在尝试将 AWS lambda 中的浮点值作为键、值对在事件中传递,为此我正在做

from decimal import Decimal
ENERGY_VERBRAUCH = event['energy_verbrauch']
ENERGY_VERBRAUCH = Decimal(str(ENERGY_VERBRAUCH))

我在事件中的键值对是

"energy_verbrauch": "2500000"

但我收到以下错误:

START RequestId: e2179e21-f225-44a1-bb99-266b184bc4e2 Version: $LATEST
unsupported operand type(s) for /: 'decimal.Decimal' and 'float'
END RequestId: e2179e21-f225-44a1-bb99-266b184bc4e2

和日志:

在此处输入图像描述

我查看了关于 SO 的一个已经存在的问题并遵循了该问题,但我仍然得到了错误。

问题:Python 3 Lambda 函数的输入 JSON 中的小数

然后ENERGY_VERBRAUCH将其传递给函数

def factorize(energy_needed, df):
    '''For scaling the Lastprofile on energy verbrauch'''
    factor = energy_needed/(df['values'].sum()/1000)
    df['values'] = (df['values']/1000)*factor
    df['values'] = df['values'].round(3)
    return df

标签: pythonpython-3.xamazon-web-servicesaws-lambda

解决方案


正如错误消息所说,Decimal值不支持float值除法。

我在事件中的键值对是

"energy_verbrauch": "2500000"

这是一个整数值。在这种情况下,使用Decimal似乎没有必要。

你可以改变

from decimal import Decimal
ENERGY_VERBRAUCH = event['energy_verbrauch']
ENERGY_VERBRAUCH = Decimal(str(ENERGY_VERBRAUCH))

ENERGY_VERBRAUCH = int(event['energy_verbrauch'])

(您也不需要使用str,因为该值已经是一个字符串。)

然后将在 anint和 a之间进行除法float,这是允许的,并且会产生另一个float


推荐阅读