在比@Danil斯佩蘭斯基與您現有的字典結構的更廣義的方法:
def sold(name, quant):
stock[name + " QUAN"][0] -= 1
我會重組藏漢字典,甚至考慮定義一個類的字典創建對象:
class store_item(object):
def __init__(self, price, condition, quantity, info1=None, info2=None):
self.price_usd = price
self.condition = condition
self.info1 = info1
self.info2 = info2
self.quant = quantity
然後,你可以用它的對象做一個字典,並以一種很好的方式訪問它(甚至可以使用繼承爲不同類型的產品創建特殊類,示例處理器)。訪問的例子:
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)
爲什麼要將值保留在「list」中?它會更容易,它只是一個整數..無論如何:'股票['英特爾i7-7770T QUAN'] [0] - = 1' –
在你跳到操作你的字典之前,我可能會重新思考的結構字典?似乎你可以通過一些關於你的鍵/值對的計劃讓自己的生活變得更容易一些 – RHSmith159