[Tutor] Counting Items in a List
mariocatch
mariocatch at gmail.com
Wed Jun 20 20:34:21 CEST 2012
Here's one way, can surely be optimized:
* paragraph = "This paragraph contains words once, more than once, and
possibly not at all either. Figure that one out. "
para = paragraph.strip('.').strip(',').strip().split()
wordDict = {}
for word in para:
word = word.strip('.').strip(',')
if wordDict.has_key(word):
wordDict[word] += 1
else:
wordDict[word] = 1*
* print wordDict
*
-Mario
On Wed, Jun 20, 2012 at 1:26 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:
> On 20/06/12 16:20, Martin A. Brown wrote:
>
> : should have written something like "counting how many times each
>> : word occured" insted of "counting words".
>>
>> You might like to try out collections.defaultdict().
>>
>
> Even a standard dict would simplify the code dramatically.
> The defaultdict does suit this case better though.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
>
> ______________________________**_________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120620/939e6167/attachment.html>
More information about the Tutor
mailing list