列表索引错误python(数字字程序)

时间:2018-12-02 12:05:37

标签: python-3.x

我正在尝试用Python 3编写程序。 它是这样工作的: 输入是一个单词。 并且程序必须查看该单词是否包含荷兰数字单词。 一个单词不能包含多个数字单词,如果一个单词不包含数字单词,则必须打印'geen'(荷兰语中没有)。

示例:

输入= BETWEEN 输出= TWEE(两个荷兰语)

输入= ZEEVERS 输出= ZES(荷兰语中为六个)

这是我的代码:

import sys

invoer = input()

letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]

antwoord = []

woord = [str(a) for a in str(invoer)]

L = len(woord)

a = 0
b = 0
c = 0

for i in range(0, 8):
    for j in range(0, len(letterwoorden[a])):
        if letterwoorden[a][b] == woord[c]:
            antwoord.append(letterwoorden[a][b])
            b = b + 1
            c = c + 1
        else:
            c = c + 1
    if antwoord == letterwoorden[a]:
        print(antwoord)
        break
    else:
        a = a + 1
        antwoord.clear()

if antwoord != letterwoorden[a]:
        print('geen')

有人可以帮助我解决第21行的错误吗? (列表索引超出范围) 谢谢! 代码没有完全完成,但是当输入为TWEET时,输出为TWEE, 当输入在BETWEEN之间时,会提示错误。

2 个答案:

答案 0 :(得分:0)

尽管usr2564301's first solution看起来不错,但我想添加一些内容。您可以在代码的注释中找到它。

这是我修改您的代码的方式:

##  use strings instead of list of strings
##  ['T', 'W', 'E', 'E'] ==> 'TWEE'
##  they are also iterable (you can loop through them)
##  as well as indexable (['T', 'W', 'E', 'E'][0] == 'TWEE'[0])

letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']

##  keep the string
woord = input()
print('Input:', woord)

##  answer should be string as well
antwoord = ''

##  name your variables something meaningful
##  how does one differentiate between b and c? smh
letterWoordenIndex = 0
woordenIndex = 0

##  for-loops can be powerful in Python
##  you might've been used to index-based loops from other languages :|
##  this way, tempWord can replace all occurrences of letterwoorden[a]
for tempWord in letterwoorden:

    ##  reset your variables at the beginning of the loop
    letterWoordenIndex = woordenIndex = 0

    # """ ##  debug output printing word
    print('Word:', tempWord, '?')
    # """

    ##  loop through the length of word
    ##  use _ to indicate that the variable won't be used
    for _ in range(len(woord)):

        # """  ##  debug output comparing letters/indices
        print(tempWord[letterWoordenIndex],
              '({})'.format(letterWoordenIndex),
              '<=>', woord[woordenIndex],
              '({})'.format(woordenIndex))
        # """

        ##  check current indices equals match
        if tempWord[letterWoordenIndex] == woord[woordenIndex]:
            antwoord += tempWord[letterWoordenIndex]    ##  append char to string using +

            ##  increment indices
            letterWoordenIndex += 1
            woordenIndex += 1

            ##  check if index is filled
            if letterWoordenIndex == len(tempWord):
                break
        else:
            woordenIndex += 1

    # """ ##  debug output comparing final results
    print(antwoord, '>==<', tempWord)
    # """

    ##  assert that the accumulated result (antwoord)
    ##  equates to the tempWord
    if antwoord == tempWord:
        # """ ##  debug assert true
        print('Yep\n')
        # """

        print(antwoord)
        break

    ##  no need to use else here
    ##  if the code inside the above if executes, then it's already game-over

    antwoord = ''   ##  empty the string

    # """ ##  debug assert false
    print('Nope\n')
    # """

##  antwoord would be empty if everything failed
if antwoord == '':
    print('GEEN')

答案 1 :(得分:-1)

您正在用行遍历错误的列表

<input asp-for="Price" class="form-control" type="number"/>

随着这又对所有for j in range(0, len(letterwoorden[a])): 增加a –您已经在第一个循环letterwoorden上遍历了letterwoorden。如果您用完了“源”字符(for i in range(0, 8):的长度)或“比较”字符(单词invoer),更改它以遍历有问题的单词会导致另一个错误。重新开始比较时,还必须注意重置woord[c]b计数器。

最后,您测试了c,但是antwoord[a]可能超出范围

以下代码有效

a

一些附加说明:如果您已经具有循环变量,则无需维护单独的变量。例如,在使用import sys invoer = input() letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'], ['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'], ['N','E','G','E','N']] antwoord = [] woord = [str(a) for a in str(invoer)] L = len(woord) a = 0 b = 0 c = 0 for i in range(len(letterwoorden)): b = 0 c = 0 for j in range(len(woord)): print ('test', a,b,c, letterwoorden[a][b], woord[c]) if letterwoorden[a][b] == woord[c]: antwoord.append(letterwoorden[a][b]) b = b + 1 if b >= len(letterwoorden[a]): break c = c + 1 else: c = c + 1 if antwoord == letterwoorden[a]: print(antwoord) break else: a = a + 1 antwoord = [] if antwoord == []: print('geen') 的地方,也可以使用循环a;与i相同。

由于Python可以立即检查一个短语是否包含另一个短语:j,因此您进行所有比较的效率都更高。所以,基本上,

if straw in haystack

invoer = 'ZEEVERS' letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN'] for word in letterwoorden: if word in invoer: print (word) break else: print ('geen') linked to the for and not to the else的地方,以检查循环是否因结果而停止。