0

リスト内の単語の数を見つけるスクリプトがあります

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生成:

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

リストnewm内の各単語の数を見つけたいのですが、エラーが発生します:

TypeError: list indices must be integers, not str

どうすれば修正できますか?

4

2 に答える 2

0

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})
于 2013-08-18T14:03:34.023 に答える