【问题标题】:sort, add and delete similar index of list of dictionary, using FIFO使用 FIFO 对字典列表的相似索引进行排序、添加和删除
【发布时间】:2019-04-17 17:30:05
【问题描述】:

我正在尝试解决这个问题,并且我得到了类似这样的字典列表。 (这是'购买方法'的字典)

[{'qty': 20, 'price': 2000.0, 'product': 'Computer', 'date': '2017-03-05'}, 
{'qty': 22, 'price': 5000.0, 'product': 'Computer', 'date': '2017-11-11'},
{'qty': 6, 'price': 1523.0, 'product': 'Computer', 'date': '2018-02-03'},
{'qty': 10, 'price': 1000.0, 'product': 'Computer', 'date': '2018-12-05'},
{'qty': 20, 'price': 2000.0, 'product': 'Computer', 'date': '2019-11-06'},
{'qty': 10, 'price': 1000.0, 'product': 'Computer', 'date': '2019-08-02'}
]

我正在尝试创建一个名为def sale(quantity, date): 的方法在这个函数中,我想传入数量和日期,如果在销售日期之前有足够的库存,它允许我销售该数量的数量。

例如如果我通过数量 = 30 和日期 = 2018-01-01 ,它应该允许我出售,因为数量足够可以出售,在此之后,剩余数量和价格应根据计算并应添加到上面的字典列表。

例如。在我们的例子中

{'qty': 12, 'price': 2000.0, 'product': 'Computer', 'date': '2018-01-01'}

并且应该删除前 2 个字典,因为我们已经卖掉了它们! (这就像库存先进先出的东西)

这是我正在尝试执行此操作的代码。但是,我遇到了错误,并且没有得到我想要的输出。还有其他可能吗?如何让它发挥作用?

import datetime
from collections import Counter

class Supplier:
    def add_supplier(self, name, address, email, contact_no):
        self.name = name
        self.address = address
        self.email = email
        self.contact_no = contact_no

class Product:
    def add_product(self, name):
    self.name = name

class Company(Supplier, Product):
    data_dict = []
    def purchase(self, product_obj, qty, price, date=datetime.date.today()):
    self.data_dict.append({'product': product_obj.name, 'qty': qty, 'price': price, 'date': str(date)})

    def sale(self, sell_qty, sell_date=datetime.date.today()):
        a = 0
        p = 0
        unit_val = 0
        new_price = 0
        newdict = (sorted(self.data_dict, key=lambda x: x['date']))

        for dt in newdict:
            a += dt['qty']
            p += dt['price']
            if sell_date > dt['date']:
                if sell_qty <= a:
                   unit_val = float(p / a)
                    new_price = unit_val * a
                    a -= sell_qty
                    self.data_dict.append({'product': product_obj.name, 'qty': a, 'price': new_price, 'date': str(sell_date)})
                    print("sold!")

            else:
                print("Sorry, not enough qty.\n")


C = Company()
PRODUCT_OBJ = Product()
PRODUCT_OBJ.add_product('Computer')

while True:

    option = int(input(" 1. You want to add stock of the product!\n2. Want to sell product?\n"))

    if option == 1:
        qty = int(input("Enter the qty of the product.\n"))
        price = float(input("Enter the price of the product.\n"))
        purchase_date = input("Enter purchase date.\n")
        C.purchase(PRODUCT_OBJ, qty, price, purchase_date)

    elif option == 2:
        qty = int(input("Enter the qty you wanna sell, pal!"))
        sale_date = input("Enter sell date.\n")
        C.sale(qty)

得到错误:

Traceback (most recent call last):
  File "G:/python/test.py", line 63, in <module>  C.sale(qty)
  File "G:/python/test.py", line 33, in sale if sell_date > dt['date']:
 TypeError: '>' not supported between instances of 'datetime.date' and 'str'

想要的输出:

[{'qty': 12, 'price': 2000.0, 'product': 'Computer', 'date': '2018-01-01'},
{'qty': 6, 'price': 1523.0, 'product': 'Computer', 'date': '2018-02-03'},
{'qty': 10, 'price': 1000.0, 'product': 'Computer', 'date': '2018-12-05'},
{'qty': 20, 'price': 2000.0, 'product': 'Computer', 'date': '2019-11-06'},
{'qty': 10, 'price': 1000.0, 'product': 'Computer', 'date': '2019-08-02'}
]

【问题讨论】:

  • 您遇到了什么错误?您的代码中的某些缩进看起来不正确。例如这一行self.name = name。
  • @Munosphere 是的,这就是产品名称“计算机”的未来修改,现在我只是在寻找 FIFO。其他用于增强目的的属性,伙计..
  • 我的意思是由于缩进错误,代码甚至无法运行。无论如何,请包括您收到的错误以及您想要的输出。
  • 将代码粘贴到您的问题后,立即选择您刚刚粘贴的内容,然后键入 Ctrl+K 或单击编辑器界面中的{} 按钮。这将自动格式化代码块,因此您在尝试手动修复时不会引入缩进错误。

标签: python dictionary inventory-management


【解决方案1】:

@adrtam 向您展示了如何修复您发布的错误。但是您的代码存在严重问题。我不会解决所有问题,但这里有一些提示:

  • 类Supplier:add_supplier 应该是__init__。您创建一个新的供应商:s = Supplier("foo", "bar", "baz@baz", "no")
  • 类Product:同上
  • 类Company:
    • 不应从Product 和Supplier 继承(公司是产品和供应商?否)
    • 错过了__init__ 方法:data_dict 当前是一个类字段,应该是一个实例字段
  • 避免使用 a、p 之类的名称:始终使用有意义的名称。
  • 在期望的输出中,没有理由在销售后将第一行的日期设置为'2018-01-01'
  • 首选动词来命名您的方法(取决于上下文):sell 而不是 sale。

现在,让我们看看sell 方法。我假设这是 FIFO 库存:您首先出售先购买的产品。 这是一个简单的想法:

  • 遍历行并对可用数量求和。
  • 只要数量足够,就退出循环
  • 然后删除浏览的行并修复最后浏览的行的数量。

示例代码(我假设数据始终按日期排序:要强制执行此操作,您可以使用priority queue):

data = [{'qty': 20, 'price': 2000.0, 'product': 'Computer', 'date': '2017-03-05'},
    {'qty': 22, 'price': 5000.0, 'product': 'Computer', 'date': '2017-11-11'},
    {'qty': 6, 'price': 1523.0, 'product': 'Computer', 'date': '2018-02-03'},
    {'qty': 10, 'price': 1000.0, 'product': 'Computer', 'date': '2018-12-05'},
    {'qty': 20, 'price': 2000.0, 'product': 'Computer', 'date': '2019-11-06'},
    {'qty': 10, 'price': 1000.0, 'product': 'Computer', 'date': '2019-08-02'}]

wanted = {'qty': 30, 'date': '2018-01-01'}

def sell(wanted):
    global data # NEVER do this: just for the example
    assert wanted['qty'] > 0
    qty = 0
    for i, row in enumerate(data):
        # too late!
        if row['date'] > wanted['date']:
            raise Exception("Sorry, not enough qty. Operation cancelled")

        qty += row['qty']
        # we have enough Computers!
        if qty >= wanted['qty']:
            break
    else: # loop completes normally
        raise Exception("Sorry, not enough qty. Operation cancelled")

    remaining_qty_in_last_row = qty-wanted['qty']
    # copy of the last row with a new quantity + the remaining rows
    data = [{**row, 'qty':remaining_qty_in_last_row}] + data[i+1:]
    print ("Sold!")

for wanted in [{'qty': 30, 'date': '2018-01-01'}, {'qty': 30, 'date': '2018-01-01'}]:
    try:
         sell(wanted)
    except e:
         print(e)
    print ("data", data)

这只是算法的草图:您必须练习以提取正确的类和方法设计。

【讨论】:

    【解决方案2】:

    让我们修复您发布的错误:

    Traceback (most recent call last):
      File "G:/python/test.py", line 63, in <module>  C.sale(qty)
      File "G:/python/test.py", line 33, in sale if sell_date > dt['date']:
     TypeError: '>' not supported between instances of 'datetime.date' and 'str'
    

    问题是您在日期时间对象中有sell_date,但您在字典中的日期是一个字符串。您需要将它们转换为相同的类型才能进行比较。两种方法:

    1. 使您的日期时间对象成为可以比较的固定格式字符串:

      if sell_date.strftime("%Y-%m-%d") > dt['date']:
      
    2. 将日期字符串解析为日期时间对象:

      import datetime
      if sell_date > datetime.datetime.strptime(dt['date'], '%Y-%m-%d'):
      

    【讨论】:

    • 谢谢你,那么其他字典部分呢?
    • 我不太清楚你的意思。但是,如果您只想删除列表中日期小于您的 sell_date 的所有字典,请使用列表理解:data_dict = [x for x in data_dict if x['date'] &gt; sell_date]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2014-02-14
    相关资源
    最近更新 更多