On Sun, Sep 13, 2020 at 2:29 AM Saurav Chirania
<chirania.sau...@gmail.com> wrote:
>
> I really like that python's sort method accepts a key function as a
> parameter which can be used to specify how elements should be compared.
>
> Similarly, we could have a "key" argument which specifies how elements
> should be counted. Let's say we have a list of a million students. I would
> like to do something like:
> c = Counter(students, key = lambda student: student.marks)
>
> which would return a Counter which maps marks to the number of students
> with that marks. Let's say 29 students in the list had scored 100 marks, so
> one entry in the counter would be key=100, val=29.
>
> So, why doesn't Counter's constructor support this argument? Are there
> other pythonic ways to do this?
>

If I'm interpreting this correctly, a comprehension should work for you:

c = Counter(student.marks for student in students)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to