如何在python中添加不同列表中的列表项?

时间:2016-01-26 19:46:39

标签: python python-2.7 python-3.x

我正在尝试在python中创建一次性pad-esque密码。为此,我将所有纯文本然后将密钥转换为ASCII代码,然后将它们一起添加,然后将它们转换回常规字符。但是,当我尝试将两个数字加在一起时,我遇到了困难。这是我的代码:

#Creating initial variables
plainText = str(input('Input your plain text \n --> ')).upper()
key = str(input('Input your key. Make sure it is as long as your plain text.\n --> ')).upper()

#>Only allowing key if it is the same size as the plain text
if len(key) != len(plainText):
    print('Invalid key. Check key length.')
    key = str(input('Input your key. Make sure it is as long as your plain text. \n --> ')).upper()
else:
    plainAscii=[ord(i) for i in plainText]
    keyAscii=[ord(k) for k in key]

print (plainAscii)
print (keyAscii)

#Adding the values together and putting them into a new list
cipherText=[]
for i in range(0, len(key)):
    x = 1
    while x <= len(key):
        item = plainAscii[x] + keyAscii[x]
        cipherText.append(item)
        x = x + 1
print(cipherText)

我在进行测试时打印列表。但是它只会在打印前两个列表后返回:

 Traceback (most recent call last):
  File "/Users/chuckii/Desktop/onetimepad.py", line 21, in <module>
    item = plainAscii[x] + keyAscii[x]
IndexError: list index out of range

请忽略我的少年用户名,我是在10岁时制作的。提前致谢。

1 个答案:

答案 0 :(得分:1)

提高效率编辑:

cipherText=[]

for i in range(len(key)):
    for x in range(len(key)):
        item = plainAscii[x] + keyAscii[x]
        cipherText.append(item)

print(cipherText)

应该解决它!