1

我对 Python 编程非常陌生,并且一直在关注一些视频和网站教程。我正在处理一些编程练习问题并且在调试时遇到了麻烦。这是我第一次练习编程。该函数接受一个字符串并将其转换为数字列表。所以'a'变成0,'b'变成1,等等。它看起来很简单,但我收到错误'IndexError:list index out of range'。我已经尝试了一些东西,但我不确定问题是什么。有人可以看看我的代码,看看我是否犯了任何明显的错误。非常感谢所有帮助!

    import sys
    import string
    import math

    def string2nlist(m):
    characters =    ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v''w''x''y''z']
    numbers = ['0''1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24''25']
    newList = []
    msgLen = len(m)         # var msgLen will be an integer of the length

    print 'Message before conversion: ' + m

    index = 0               # iterate through message length in while loop
    while index < msgLen:
        letter = m[index]   # iterate through message m
        i = 0
        while i < 26:
            if letter == characters[i]:
                newList[index] = numbers[i]
            i = i + 1
        index = index + 1
    print newList
    return newList


    message = 'hello'
    newMessage = string2nlist(message)

    print 'Message after conversion: ', newMessage
4

2 回答 2

0

您的列表格式似乎不正确。尝试:

characters =    ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
numbers = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25']
于 2013-03-29T16:56:25.817 回答
0

这:

characters = ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v''w''x''y''z']
numbers = ['0''1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24''25']

Python compiles adjacent string literals into a single string. This is useful in many cases, but unfortunately it means that it turned your lists into:

characters = ['abcdefghijklmnopqrstuvwxyz']
numbers = ['012345678910111213141516171819202122232425']

As was mentioned, add commas in between the characters.

于 2013-03-29T16:59:13.080 回答