如何在字典循环中添加负数?

时间:2020-05-05 23:17:18

标签: python

我从中得到了非常奇怪的结果,这很简单。我一定想念一些东西,作为一个新手,我敢肯定是这样。

我从产品销售数据库中提取记录,需要将结果格式化为多个字典,才能将其输入Excel。我已经简化了示例,但想法是default词典具有更多的属性,并且我们基于该属性创建了许多不同的产品销售分组。

products = {}

for item in records:

    units = int(item['quantity'])
    weight = float(item['weight'])

    print(item['name'] + ' adding: ' + str(weight))

    default = {'sku': item['sku'],
                'product_name': item['name'],
                'units': units,
                'weight': weight}

    if item['sku'] in products:
        if units < 0:
            products[item['sku']]['units']  -= abs(units)
            products[item['sku']]['weight'] -= abs(weight)
        else:
            products[item['sku']]['units']  += (units)
            products[item['sku']]['weight'] += (weight)
    else:
        products[item['sku']] = default

    products[item['sku']]['weight'] = round(products[item['sku']]['weight'], 4)
    print(item['name'] + ' total: ' + str(products[item['sku']]['weight']))

如果该产品尚未在词典中,则我将其添加为默认的二级词典作为其值。

下次我们遇到该产品时,我想添加所售商品的数量和总重量。不同的产品具有不同的权重,因此每个产品的总运行量是有效的。

问题是,当单位/权重为负数时,它们会完全擦除以前的值,因此,如果总单位为1200,而下一次迭代为-5,则总和为-5。

尽管我使用Python中的5 + -2 = 3,但我只是想不明白为什么会这样,所以我添加了if语句并减去了abs的值,但这也不起作用。 / p>

编辑

添加一些数据以供参考

sku, name, units, weight
'548313', 'Product 2', '72', '0.3406'
'469981', 'Product 1', '936', '4.4268'
'469981', 'Product 1', '24', '0.1135'
'191004', 'Product 3', '480', '2.2700'
'469981', 'Product 1', '72', '0.3406'
'191004', 'Product 3', '576', '2.7242'
'212220', 'Product 4', '24', '0.1135'
'469981', 'Product 1', '624', '2.9511'
'469981', 'Product 1', '912', '4.3137'
'469981', 'Product 1', '-8', '-2.4000'
'548313', 'Product 2', '648', '3.0647'
'548313', 'Product 2', '48', '0.2270'
'548313', 'Product 2', '360', '1.7025'
'191004', 'Product 3', '24', '0.1135'
'191004', 'Product 3', '48', '0.2270'
'191004', 'Product 3', '456', '2.1567'
'817564', 'Product 6', '-1', '-0.3000'
'191004', 'Product 3', '576', '2.7242'
'212220', 'Product 4', '-1', '-0.3000'
'415116', 'Product 5', '480', '2.2703'
'415116', 'Product 5', '24', '0.1135'
'817564', 'Product 6', '48', '0.2270'
'548313', 'Product 2', '648', '3.0647'

1 个答案:

答案 0 :(得分:0)

根据我认为已删除的评论,我弄清楚了。每次都设置default字典是导致计算异常的原因。

一旦将字典创建复制到我使用引用的所有实例中,它就会相应地进行计算。

我猜测这是Python,因为根据我的经验,循环范围内的任何变量都将使用当前值重新初始化。我觉得这很奇怪。无论如何,那是我整天都无法回去的一天。