[Tutor] Counting Items in a List

Oğuzhan Öğreden ogreden at gmail.com
Wed Jun 20 14:53:14 CEST 2012


Hi,

I have been learning Python and trying little bits of coding for a while.
Recently I tried to have a paragraph and create a list of its words, then
counting those words. Here is the code:

 import re
>
>
>> a = """Performs the template substitution, returning a new string.
>> mapping is any dictionary-like \
>
> object with keys that match the placeholders in the template.
>> Alternatively, you can provide keyword \
>
> arguments, where the keywords are the placeholders. When both mapping and
>> kws are given and there \
>
> are duplicates, the placeholders from kws take precedence."""
>
>
>> b = []
>
> c = 0
>
>
>> for y in a.split(" "):
>
> b.append(y.lower())
>
>  if  re.search(",", y) != None:
>
>  c = b.index(y.lower())
>
>  b.remove(y.lower())
>
>  b.insert(c, y.strip(",").lower())
>
>  b.sort()
>
>  b.extend(["you"])
>
>  count = 0
>
>
>> for x in b:
>
>  count = b.count(x)
>
>   if count > 1:
>
>  c = b.index(x)
>
>  if b[c+1] != x is True:
>
>  print "%s listede %d tane var." % (x, count)
>
>  else:
>
>  print "%s listede %d tane var." % (x, count)
>
>
>>
And here are the questions:


   - This code doesn't print for the items that occur more than one time.
   Why?
   - And actually as I was writing, I realized that "if b[c+1]" may return
   an error if the last item on the list occured more than one, however, it
   didn't even if a manually made the last item occur two times. Was my
   initial expectation a false one? If not, how could I turn it into a b[c-1]
   so that it will not fail in first item?

Thanks,
Oğuzhan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120620/9cd39893/attachment.html>


More information about the Tutor mailing list