Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

sorting - 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():
             setattr(self, key, value)

And examples of this record can be:

r1 = Record(uid='001',url='www.google.com',status=200)
r2 = Record(uid='002',url='www.google.com',status=404)
r3 = Record(uid='339',url='www.ciq.com', status=200)
...

What I want is to count how many users each url has. So for "google", there are '001' and '002'. I usually use a Counter to record elements within a list and their appearances. But here, Counter seems just put the elements instead of counting them. Is there a lambda I can put or try?

I can go through all the staff though...

I think i may cause confusion here.

My key point is to group the objects by its attributes...So not only the url counting but also,

res = Counter(r)

(don't know how to put lambda inside or even that's possible) I can get maybe

res[0].url = 'www.google.com'

and its count is 2..?

And suggestion?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...