Python:如何向字典中的现有值添加值

2024-05-21 05:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 3.6

你好,正在为学校编写一个股票管理程序,我不知道如何在字典中的现有数字上加1。所以我有一个条目的数量存储在字典中,但是我不知道如何让Python在数量数字上加1。代码如下所示:

stock = {'Intel i7-7770T' : ['Intel i7-7770T', '$310', 'New','1101'],
         'Intel i7-7770T QUAN' : [3]}

我需要定义一个函数吗?所以如果我卖一台英特尔i7-7770T,那么“英特尔i7-7770T全”应该变成2。或者如果我有更多的股票,它应该变成4。我怎么能做到这一点?任何帮助将不胜感激。谢谢您!在

另外,添加是通过使用Tkinter的按钮完成的,我已经弄明白了。所以如果这是通过一个函数来完成的,我只需要将按钮链接到函数上。在


Tags: 函数代码目的new数量字典stock数字
3条回答

试试这个:

stock['Intel i7-7770T QUAN'][0] += 1

我会重新编排整个句子:

stock = {
    'Intel i7-7770T': {
        'price_USD': 310,
        'condition': 'New',
        'whatever': '1101',   # should this really be a string, or is it always a number?
        'quantity': 3
    },
    ...
}

然后你可以做类似stock['Intel i7-7770T']['quantity'] += 1

其他操作也应该更容易些。 八折优惠:

^{pr2}$

从库存中删除整件商品:

stock.pop('Intel i7-7770T')

在一个比@Danil Speransky更通用的方法中,使用您当前的dict结构:

def sold(name, quant):
    stock[name + " QUAN"][0] -= 1

我也会重新构造dict,甚至考虑定义一个类来创建dict中的对象:

^{pr2}$

然后,您可以使用dict中的对象,并以一种很好的方式访问它(甚至可以使用继承为不同类型的产品(例如处理器)创建特殊的类)。访问示例:

stock['Intel i7-7770T'].quant -= 1
stock['Intel i7-7770T'].price_usd *= 0.95

使用类有一个优点,即可以向对象中写入额外的初始化,并创建对对象执行某些操作的方法。例如,折扣可以通过保留原有价值的不同方式进行:

class store_item(object):
    def __init__(self, price, condition, quantity, discount=None, info1=None, info2=None):
        self.price_usd = price
        self.discount = discount
        self.condition = condition
        self.info1 = info1
        self.info2 = info2
        self.quant = quantity

   def get_price(self, unit):
       if self.discount is None:
           return getattr(self, "price_" + unit)
       else:
           return getattr(self, "price_" + unit) * (1 - self.discount)

相关问题 更多 >