[英]How do I count up each unique occurrence of class in list? (Python)
Background:背景:
I am in the process of creating a script, which creates a production list for a small catering firm.我正在创建一个脚本,该脚本为一家小型餐饮公司创建了一份制作清单。 The list should contain three columns (product type, quantity, variant)
该列表应包含三列(产品类型、数量、变体)
Problem:问题:
I have defined a class, which contains information in the order (product type, quantity, variant)我定义了一个类,其中包含订单中的信息(产品类型、数量、变体)
class vareclass:
def __init__(self, vare, qty, meta):
self.vare = vare
self.qty = qty
self.meta = meta
For each product form each order, which is exported from the webshop, I add a class object to a list.对于从网上商店导出的每个订单的每个产品,我将一个类对象添加到列表中。
varer.append( vareclass(vare, qty, meta) )
This means, that some products appear multiple times, as more people have ordered them.这意味着,随着越来越多的人订购它们,某些产品会出现多次。
How do i count each unique ordered product variant (taking quantity into consideration)?我如何计算每个独特的订购产品变体(考虑数量)?
You can override __eq__
and __hash__
and count the products with dictionary or with collections.Counter
您可以覆盖
__eq__
和__hash__
并使用字典或collections.Counter
计算产品
class vareclass:
def __init__(self, vare, qty, meta):
self.vare = vare
self.qty = qty
self.meta = meta
def __eq__(self, other):
return self.vare == other.vare and self.qty == other.qty
def __hash__(self):
return hash(self.vare) + hash(self.qty)
def __repr__(self): # just for the print
return f'{self.vare} {self.qty} {self.meta}'
varer = [vareclass('asd', 3, 'asd'), vareclass('asd', 4, 'asd'), vareclass('asd', 3, 'asd'), vareclass('zxc', 3, 'qwe')]
d = {}
for varec in varer:
d[varec] = d.get(varec, 0) + 1
print(d) # {asd 3 asd: 2, asd 4 asd: 1, zxc 3 qwe: 1}
print(collections.Counter(varer)) # Counter({asd 3 asd: 2, asd 4 asd: 1, zxc 3 qwe: 1})
将它们存储在 集合中,因为集合是唯一对象的集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.