简体   繁体   English

列表迭代中的Python“列表索引超出范围”错误

[英]Python “list index out of range” error in list iteration

What am I doing Wrong? 我究竟做错了什么? "list index out of range" on line 7 Sorry for russian letters in code, it's my hometask. 第7行上的“列表索引超出范围”对不起,代码中的俄语字母是我的任务。 Help me please. 请帮帮我。

import sys
morze = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
ralphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' #Russian alphabet 0-32
doc = "Вот цитата для тебя : Встретив двусмысленность , отбрось искушение угадать . С наилучшими пожеланиями , Андрей ." #doc = open('text.txt') 
print('Не поддерживается правильное отображение знаков препинания. Ставьте знаки через пробел.') #Attention
for line in doc:
    line = line.lower() #Downcase
    for word in line.split(' '):
        ln = len(word) #Length of word
        if ln == 1 and word in ralphabet: #One-letter words
            letternumber = ralphabet.find(word)
            sys.stdout.write(morze[letternumber] + ' ')
        elif ln == 1: #Symbols
            ...
        elif ln != 1 and not (word[0] in alphabet): #Symbols error
            sys.stdout.write('[ERROR]')
        elif ln != 1: #Long words
            shift = ln - 1
            if shift > 10:
                shift = 10
            for letter in word:
                letternumber = ralphabet.find(letter) + 1 - shift
                for digit in str(letternumber):
                    sys.stdout.write(morze[digit] + ' ')
            sys.stdout.write('| ')
        sys.stdout.write('| ')

input() #PAUSE

You are using the index of the word to find something in the morze list if you print(letternumber,len(morze)) you can see exactly why you get the error: 如果使用print(letternumber,len(morze))则使用单词的索引在morze列表中找到某些print(letternumber,len(morze))您可以确切地知道为什么会收到错误:

  (31, 10)
   ^    ^   

The length of ralphabet is 66 and the length of morze is 10 so that is not going to work. ralphabet的长度为66ralphabet的长度为10因此无法正常工作。

You might also want to change these two lines: 您可能还想更改这两行:

 elif ln > 1 and word[0] not in alphabet:  #Symbols error
            sys.stdout.write('[ERROR]')
 elif ln > 1:  #Long words

0 is also != 1 but word[0] is not going to work . 0也是!= 1,但是word[0]无效。

You are also calling str on letternumber then trying to pass a string as an index: 您还要在letternumber上调用str ,然后尝试将字符串作为索引传递:

       for digit in str(letternumber):
             sys.stdout.write(morze[digit] + ' ')
                                       ^
                                       string = error

You could use: 您可以使用:

  for digit in range(letternumber):
         sys.stdout.write(morze[digit] + ' ')

But again if letternumber = ralphabet.find(letter) + 1 - shift is greater than 10 you would get an error. 但是,如果letternumber = ralphabet.find(letter) + 1 - shift大于10,则会再次出现错误。

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

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