无法解决问题,列出索引超出范围(在 3 个循环内)



我知道list index out of range以前已经被覆盖了一百万次,我知道问题可能是我试图引用一个不存在的索引位置,但由于嵌套了3个for循环,我无法弄清楚发生了什么。

我正试图计算单词表中每个字母的频率。

alphabet_string = string.ascii_uppercase
g = list(alphabet_string)
a_count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
y = 0
for word in words:
for chars in word:
for letters in chars:
if letters == g[y]:
a_count[y] = a_count[y] +1
y = y + 1
print(a_count[0])

word的格式为:['ZYMIC']

chars的格式为:ZYMIC

letters的格式为:C

如果我用y值替换0到25之间的值,那么它会按预期返回。我有一种感觉,问题如上所述,我超过了25的索引号,所以我猜y = y + 1的位置不对。然而,我在不同的位置上尝试过。

如有任何帮助,我们将不胜感激。

谢谢!

编辑:非常感谢大家,以前从未收到过这么多回复,都很有帮助!

a_count存储为字典是解决此问题的更好选择。

a_count = {}
for word in words:
for chars in word:
for letters in chars:
a_count[letters] = a_count.get(letters, 0) + 1

也可以使用collections库中的Counter()类。

from collections import Counter
a_count = Counter()
for word in words:
for chars in word:
for letters in chars:
a_count[letters] += 1
print(a.most_common())

通过Counter-的解决方案

from collections import Counter
words = ['TEST','ZYMIC']
print(Counter(''.join(words)))

如果你想坚持你的代码,那么改变if condition-

y=0时,g[y]表示"A",并且您正在检查'A' == 'Z'是否为第一个字母。基本上,您需要从列表g中获取元素的索引位置,并将值增加1。这就是你需要做的,让它发挥作用。如果我正确理解你的问题。

import string
words = ['ZYMIC']
alphabet_string = string.ascii_uppercase
g = list(alphabet_string)
a_count = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for word in words:
for chars in word:
for letters in chars:
if letters in g:
y = g.index(letters)
a_count[y] += 1
print(a_count)

你可以很好地替换if condition,并直接检查索引,因为字母总是在g中。因此,这个特殊条件在这里是多余的。

for word in words:
for chars in word:
for letters in chars:
y = g.index(letters)
a_count[y] += 1

我认为这是因为列表a_count。我在这里建议另一种基于字典的方法:

listeletters = ['foihroh','ZYMIC','ajnaisui', 'fjindsonosn']
alphabeth = {'a' : 0, 
'b' : 0,
'c': 0}
for string in listeletters:
for l in string:
if l in alphabeth.keys():
alphabeth[l] = alphabeth[l] + 1
print(alphabeth)

我初始化了alphabeth,然后我得到了想要的结果

最新更新