count

Vilya Harvey vilya.harvey at gmail.com
Wed Jul 8 04:56:55 EDT 2009


2009/7/8 Dhananjay <dhananjay.c.joshi at gmail.com>:
> I wanted to sort column 2 in assending order  and I read whole file in array
> "data" and did the following:
>
> data.sort(key = lambda fields:(fields[2]))
>
> I have sorted column 2, however I want to count the numbers in the column 2.
> i.e. I want to know, for example, how many repeates of say '3' (first row,
> 2nd column in above data) are there in column 2.

One thing: indexes in Python start from 0, so the second column has an
index of 1 not 2. In other words, it should be data.sort(key = lambda
fields: fields[1]) instead.

With that out of the way, the following will print out a count of each
unique item in the second column:

from itertools import groupby
for x, g in groupby([fields[1] for fields in data]):
    print x, len(tuple(g))

Hope that helps,
Vil.



More information about the Python-list mailing list