Python How To Use Counter On Objects According To Attributes
I have a class named record, which stores information of log record; class Record(): def __init__(self, **kwargs): for key, value in kwargs.items(): setatt
Solution 1:
You should be able to just iterate over all the records and pass url values to Counter, like so:
records = [r1, r2, r3, ...]
url_counter = Counter(r.url for r in records)
print(url_counter['www.google.com'])
Solution 2:
There was a subtle bug in my previous answer, and while fixing it I came up with a much simpler and faster way to do things which no longer uses itertools.groupby()
.
The updated code below now features a function designed to do exactly what you want.
from collections import Counter
from operator import attrgetter
class Record(object):
def __init__(self, **kwargs):
for key, value in kwargs.iteritems():
setattr(self, key, value)
records = [Record(uid='001', url='www.google.com', status=200),
Record(uid='002', url='www.google.com', status=404),
Record(uid='339', url='www.ciq.com', status=200)]
def count_attr(attr, records):
""" Returns Counter keyed by unique values of attr in records sequence. """
get_attr_from = attrgetter(attr)
return Counter(get_attr_from(r) for r in records)
for attr in ('status', 'url'):
print('{!r:>8}: {}'.format(attr, count_attr(attr, records)))
Output:
'status': Counter({200: 2, 404: 1})
'url': Counter({'www.google.com': 2, 'www.ciq.com': 1})
Post a Comment for "Python How To Use Counter On Objects According To Attributes"