-2

我正在 python 中制作一个简单的替换密码。我希望这个程序遍历字符串中的字符,然后将它们的数值添加到数组中,但它给了我这个错误: Traceback (most recent call last): File "D:\py programs\simple cypher.py", line 39, in <module> x[i]=18 IndexError: list assignment index out of range 这是我的代码:

pt=raw_input('string to encrypt ')
x=[]
for i in range (0, len(pt)):
    if pt[i]=='a':
        x[i]=1
    elif pt[i]=='b':
        x[i]=2
    elif pt[i]=='c':
        x[i]=3
    elif pt[i]=='d':
        x[i]=4
    elif pt[i]=='e':
        x[i]=5
    elif pt[i]=='f':
        x[i]=6
    elif pt[i]=='g':
        x[i]=7
    elif pt[i]=='h':
        x[i]=8
    elif pt[i]=='i':
        x[i]=9
    elif pt[i]=='j':
        x[i]=10
    elif pt[i]=='k':
        x[i]=11
    elif pt[i]=='l':
        x[i]=12
    elif pt[i]=='m':
        x[i]=13
    elif pt[i]=='n':
        x[i]=14
    elif pt[i]=='o':
        x[i]=15
    elif pt[i]=='p':
        x[i]=16
    elif pt[i]=='q':
        x[i]=17
    elif pt[i]=='r':
        x[i]=18
    elif pt[i]=='s':
        x[i]=19
    elif pt[i]=='t':
        x[i]=20
    elif pt[i]=='u':
        x[i]=21
    elif pt[i]=='v':
        x[i]=22
    elif pt[i]=='w':
        x[i]=23
    elif pt[i]=='x':
        x[i]=24
    elif pt[i]=='y':
        x[i]=25
    elif pt[i]=='z':
        x[i]=26
    elif pt[i]==' ':
        x[i]='_'
print x

有人可以帮忙吗?

4

5 回答 5

1

http://docs.python.org/2/library/string.html

string.maketrans(from, to) Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.

Assign the translated to a separate list possibly? If this is what your looking for...

input_alphabet="abcde"  
output_alphabet="12345"  
trantab = maketrans(input_alphabet,output_alphabet)  
text="translate abcdefg"  
print text.translate(trantab)  
于 2013-11-01T16:59:58.433 回答
1

在 Python 中,你不能分配一个大于列表长度的索引,所以你的每一x[i] = ...行都会导致这个 IndexError。

相反,您需要将所有这些更改为x.append(...),这将在列表末尾添加一个新元素。

但实际上,您的整个代码可以重构,使其更短:

import string

pt = raw_input('string to encrypt ')
trans = {c: i for i, c in enumerate(string.lowercase, 1)}
trans[' '] = '_'
x = [trans[c] for c in pt if c in trans]
print x
于 2013-11-01T16:23:20.250 回答
1

What you currently are trying to do is better written like this:

pt = raw_input('string to encrypt ')
x = [ord(i)-96 for i in pt]

If this really is what you need depends on what you intended to do next, but hopefully that takes you a bit further.

于 2013-11-01T16:33:59.210 回答
0

您的列表x是空的,因此没有x[i]分配给:正如错误消息所述。相反,使用x.append(...). 或者定义xx = [None] * len(pt)有插槽可以填充。

当然,有很多、更简单、更短的方法来做你想做的事情。试试字典,或者translate()字符串的方法。

于 2013-11-01T16:18:33.400 回答
-1

该列表是空的,您需要的是:

x.insert(i,1)

1在索引中插入值i

于 2013-11-01T16:19:34.437 回答