简体   繁体   English

Python“列表索引超出范围”

[英]Python “list index out of range”

I am having a bit of trouble with the following code. 我在使用以下代码时遇到麻烦。 I am translating a phrase from English to pig latin and seem to encounter the following problem despite the numerous workarounds I have tried 尽管我尝试了多种解决方法,但我正在将短语从英语翻译成猪拉丁语,似乎遇到以下问题

Traceback (most recent call last):
File "C:/Users/PMARINA/Documents/Python/YI_WordEnkryption.py/PM_PhraseEnkryption.py">    , line 37, in <module>
english = wordlist[wordcount]
IndexError: list index out of range

Code: 码:

import string
import re
english = (input('English --> Pig Latin:  ')).lower()
overlist = re.sub("[^\w]", " ",  english).split()
overcounter = len(overlist) -1
counter = 0
count = 0
wordcount = 0
wordlist = []
vowels = ['a','e','i','o','u','y','A','E','I','O','U','Y']
counter = 0
vlist = []
clist = []
vlength = len(vowels) -1
while counter <=vlength:
        vlist.append(vowels[counter])
        counter +=1
consonants = string.ascii_letters
clength = len(consonants) -1
counter = 0
while counter <= clength:
    clist.append(consonants[counter])
    counter +=1
clist.remove('A')
clist.remove('E')
clist.remove('I')
clist.remove('O')
clist.remove('U')
clist.remove('Y')
clist.remove('a')
clist.remove('e')
clist.remove('i')
clist.remove('o')
clist.remove('u')
clist.remove('y')
while count<= overcounter:
        english = wordlist[wordcount]      # Line 37
        length = len(english) -1
        while counter <=length:
            enlist.append(english[counter])
            counter +=1
        if enlist[0] in vlist:
            enlist.append(enlist[0])
            enlist.append('way')
            enlist.remove(enlist[0])
        else:
            enlist.append(enlist[0])
            enlist.append('ay')
            enlist.remove(enlist[0])
        wordlist.append(''.join(enlist))

    wordcount +=1
    count +=1
    counter = 0
    overcounter+=1
print(wordlist)

The wordlist list is empty 单词表列表为空

What you are trying to do is equivalent to this: 您要尝试执行的操作与此等效:

>>> test = []
>>> test[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

on an unrelated note, you could shorten this code: 在不相关的注释上,您可以缩短以下代码:

clist.remove('A')
clist.remove('E')
clist.remove('I')
clist.remove('O')
clist.remove('U')
clist.remove('Y')
clist.remove('a')
clist.remove('e')
clist.remove('i')
clist.remove('o')
clist.remove('u')
clist.remove('y')

to this: 对此:

for letter in vowels:
    clist.remove(letter)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM