freq function
Chris Rebert
clp2 at rebertia.com
Sun Aug 22 04:34:33 EDT 2010
On Sun, Aug 22, 2010 at 1:16 AM, Shashwat Anand
<anand.shashwat at gmail.com> wrote:
> On Sun, Aug 22, 2010 at 1:31 PM, Dirk Nachbar <dirknbr at gmail.com> wrote:
>> Here is a function which takes any list and creates a freq table,
>> which can be printed unsorted, sorted by cases or items. It's supposed
>> to mirror the proc freq in SAS.
>>
>> Dirk
>>
<snip>
>> freq={}
>> for s in seq:
>> if s in freq:
>> freq[s]+=1
>> else:
>> freq[s]=1
>
> The above code can be replaced with this:
> freq = {}
> for s in seq:
> freq[s] = freq.get(s,0) + 1
Which can be further replaced by:
from collections import Counter
freq = Counter(seq)
Using collections.defaultdict is another possibility if one doesn't
have Python 2.7.
Cheers,
Chris
--
It really bothers me that Counter isn't a proper Bag.
http://blog.rebertia.com
More information about the Python-list
mailing list