2016-10-11 30 views
0

所以我有这样一本字典:理货及在字典排序Class对象元素

{'key1': [<__main__.OrderRecord object at 0x02C70C90>], 'key2': [<__main__.OrderRecord object at 0x02C709B0>, <__main__.OrderRecord object at 0x02BC9AB0>], 'key3': [<__main__.OrderRecord object at 0x02C2F2B0>]} 

Class对象包含以下元素:

class OrderRecord: 
"""The OrderRecord class 
Data attributes: date of type str 
       location of type str 
       name of type str 
       colour of type str 
       ordernum of type int 
       cost of type int 
""" 

def __init__(self, file_line): 
    """Takes a given file line and initialises an OrderRecord instance""" 

    split_file = file_line.split(",") 
    self.date = split_file[0] 
    self.location = split_file[1] 
    self.name = split_file[2] 
    self.colour = split_file[3] 
    self.ordernum = split_file[4] 
    self.costs = self.cost_of_order() 

我需要做的是get是Class对象中的所有不同颜色(每个对象只有1个颜色,但它们可以与其他对象中的颜色相同),然后是包含该颜色的对象数量的统计。

输出结果是这样的:

Colour variables:  No. of objects:  
Colour1     2 
Colour2     1 
Colour3     1 
...     ... 

等等等等

我想我可以通过从原始文件数据服用它,只是索引到它与一个for循环获取的信息或有些东西,但我只是认为直接读取Class对象会更容易,如果可以的话?请注意,某些键可以包含多个Class对象的单个列表。

回答

0

这是使用collections.counter

from collections import Counter 

object_dict = {'key1': [<__main__.OrderRecord object at 0x02C70C90>]} 
cnt = Counter() 
for item_group in object_dict.values(): 
    for item in item_group: 
     cnt[item.color] += 1 

然后你就可以访问有关从cnt计数器对象计数的各种信息的好机会,有各种方法,如most_common,你可能会发现有用的。