Python Can';I don’’我无法解决这个问题,列表索引超出范围(在3个循环内)
我知道Python Can';I don’’我无法解决这个问题,列表索引超出范围(在3个循环内),python,Python,我知道列表索引超出范围之前已经被讨论过一百万次了,我知道问题可能是我试图引用一个不存在的索引位置,但由于嵌套了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:
列表索引超出范围
之前已经被讨论过一百万次了,我知道问题可能是我试图引用一个不存在的索引位置,但由于嵌套了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
字母
的格式为:C
如果我用y值替换0到25之间的值,那么它将按预期返回。
我感觉问题如上所述,我超出了25的索引编号,因此我猜y=y+1
处于错误的位置。不过,我在不同的位置尝试过
任何帮助都将不胜感激
谢谢
编辑:非常感谢大家,以前从未有过这么多回复,都非常有用 我想这是因为列表a\u计数。 我在此建议另一种基于词典的方法:
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)
我将字母表初始化,然后得到想要的结果存储
a_计数
,因为字典是解决此问题的更好选择
a_count = {}
for word in words:
for chars in word:
for letters in chars:
a_count[letters] = a_count.get(letters, 0) + 1
您还可以使用集合
库中的计数器()
类
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())
通过
计数器解决方案
-
from collections import Counter
words = ['TEST','ZYMIC']
print(Counter(''.join(words)))
如果您想坚持您的代码,请更改If条件
-
当y
=0g[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)
如果条件,您可以很好地替换,并直接检查索引,因为字母始终在g中。因此,这个特殊条件在这里是多余的
for word in words:
for chars in word:
for letters in chars:
y = g.index(letters)
a_count[y] += 1
你应该把字母表中的字母作为外循环来循环。还有很多其他的改进可以做,但那是另一个时间/问题/stackexchange站点的改进。这将非常有帮助,将您的所有代码减少到基本上一行。但是,作为一种良好的学习体验,请首先使用您自己的代码对问题进行排序。否则你只会使用你从互联网上抓到的随机黑盒。据我所知,y是增加的(单词*#它们的#图表)倍。我不知道有多少个图表,但肯定的是图表的数量超过了len(a_计数),那么就会有问题。我想也许你必须在if声明下增加。但是你应该根据你的目标来决定