字典中的十进制列表到浮点列表



我有来自mssql查询的列表,其中包括小数。如:

[(1, Decimal('33.00'), Decimal('5.30'), Decimal('50.00')),
(2, Decimal('17.00'), Decimal('0.50'), Decimal('10.00'))]

我想像这样将其转换为字典和浮点数:

{1: [33.00, 5.30, 50.00],
2: [17.00, 0.50, 10.00]}

我在下面写了一行:

load_dict = {key: values for key, *values in dataRead}

其结果是:

{1: [Decimal('33.00'), Decimal('105.30'), Decimal('25650.00')],
2: [Decimal('17.00'), Decimal('40.50'), Decimal('10000.00')]}

我问的是,无论如何,是否可以通过列表/字典理解进行这种转换?

您可以使用带有强制转换的字典理解来float如下:

from decimal import Decimal
lst = [(1, Decimal('33.00'), Decimal('5.30'), Decimal('50.00')),
(2, Decimal('17.00'), Decimal('0.50'), Decimal('10.00'))]
ret = {key: [float(f) for f in values] for key, *values in lst}
print(ret)
# {1: [33.0, 5.3, 50.0], 2: [17.0, 0.5, 10.0]}

将浮点数应用于值:

from decimal import Decimal
data = [(1, Decimal('33.00'), Decimal('5.30'), Decimal('50.00')),
(2, Decimal('17.00'), Decimal('0.50'), Decimal('10.00'))]
load_dict = {key: list(map(float, values))  for key, *values in data}
print(load_dict)

输出

{1: [33.0, 5.3, 50.0], 2: [17.0, 0.5, 10.0]}

最新更新