简体   繁体   中英

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

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})

将它们存储在 集合中,因为集合是唯一对象的集合。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM