user2675742
user2675742

Reputation: 117

Code to find count in list generates error

I have a script to find the count of some word in a list

newm =[]
for i in range(0,len(alpha)-1):
    newm.append (alpha[i][0])
print newm
#count for list
word_counter =[]
for word in newm:
  print word
  if word in word_counter:
      word_counter[word] += 1
  else:
      word_counter[word] = 1

newm generates:

['today', 'alpha', 'radiation', 'helium', 'work', 'charge', 'model', 'atom', 'discovery', 'interpretation', 'scattering', 'gold', 'foil', 'splitting', 'atom', 'reaction', 'nitrogen', 'alpha']

I want to find the count of each word in the list newm however it gives the error:

TypeError: list indices must be integers, not str

How can i fix it?

Upvotes: 0

Views: 69

Answers (2)

keyser
keyser

Reputation: 19189

How about using a dictionary:

word_counter = {}

if word in word_counter:
    word_counter[word] += 1
else:
    word_counter[word] = 1

The if/else is used to check if the dictionary already contains the word. If it does, it will increment its associated value, if it doesn't, it initializes the value to 1.

Python dictionaries.

And, to find out more about why your code wasn't working, here's more on lists.

As mentioned by Ashwini Chaudhary you can also use collections.Counter whose purpose is to do this kind of thing:

>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

and here's an example of how to initalize it directly from an iterable:

>>> c = Counter(['eggs','ham'])
>>> c
Counter({'eggs': 1, 'ham': 1})
>>> c['bacon']
0
>>> c['ham']
1

Examples taken from: collections: Counter Objects

Upvotes: 2

Developer
Developer

Reputation: 8400

Here is another solution using defaultdict.

In [23]: from collections import defaultdict
In [24]: data = ['a','b','c','a','b','b','d']
In [25]: counts = defaultdict(int)
In [26]: for x in data: counts[x]+=1
In [27]: counts
Out[27]: defaultdict(<type 'int'>, {'a': 2, 'c': 1, 'b': 3, 'd': 1})

Upvotes: 0

Related Questions