使用pyhon使用字典,对象对象概念对数据进行排序

时间:2019-03-26 18:36:00

标签: python oop dictionary inventory-management

我已经以常规方式实现了此示例,但是我想通过python的opps概念来实现这一目标,因此该如何实现。我在使用oops时遇到困难。

例如 按日期升序列出公司从不同供应商购买的产品数量。如果在同一日期从同一供应商处购买了同一产品,则应在输出时将其合并。

sample output
------
Supplier A
01-01-2019      Product A       10
02-02-1019      Product B       5
03-03-2019      Product A       15

Supplier B
01-01-2019      Product A       8
31-01-2019      Product B       20

使用类并使用对象-供应商,公司,产品

我已经用常规方法完成了(下面编写程序),但是我想使用纯正的概念并使用Product ..和Supplier ....的对象来实现它,

from itertools import groupby
from operator import itemgetter
class Product:
#init
def __init__(self, date=0, product_name=0,qty=0,supplier=0):
    self.product_name = product_name
    self.date = date
    self.qty = qty
    self.supplier= supplier
    #make self.my_dict
    self.my_dict={}
    self.my_list = []

def purchase(self, date, product_name, qty, supplier_name ):
    self.my_list.append([supplier_name,date,product_name,qty,])
    '''
    #make a new key if needing
     try:
         #add the data to the list
         self.my_dict[supplier_name].append([date,product_name,qty])
     except:
         #make a new list with data
         self.my_dict[supplier_name] = [[date,product_name,qty]]
    '''
 def calculation(self):
    # sort by supplier_name and group items by supplier_name,
  date,     product_name
    x = groupby(sorted(self.my_list, key=itemgetter(0)), itemgetter(slice
  (None, 3)))
    # sum the quantities
    y = [i + [sum(map(itemgetter(3), j))] for i, j in x]
    # group items by supplier
    z = [(i, list(map(itemgetter(slice(1, None)), j))) for i, j in groupby
 (y, itemgetter(0))]
    # output
    for supplier, values in z:
        print("{0}:".format(supplier))
        print("\n".join(map(str, values)))

choice=None
p=Product()
while True:
choice=int(input("1 for the add record\n2 For the display result.\n"))
if choice == 1:
    product_name=input("Enter the product name\n")
    qty = int(input("Enter the qty.\n"))
    date= input("Enter the date")
    supplier_name = input("Enter the supplier name.\n ")
    p.purchase(date,product_name,qty, supplier_name)

elif choice == 2:
    p.calculation()

0 个答案:

没有答案