【发布时间】:2018-11-21 03:32:22
【问题描述】:
谁能帮我找出这个错误?
这是一个加密/解密游戏的代码。
import random
import itertools
"""Defines the alphabet list and number list used to make the dictionaries for encoding/decoding."""
alph = ['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']
num = range(0, 26)
"""Creates the dictionaries used to encode/decode"""
alph_to_num = dict(zip(alph, num))
num_to_alph = dict(zip(num, alph))
def vigenere_encode(text):
key = 'lemon'
text = text.lower()
k = itertools.cycle(key)
key_list = []
encoded_list = []
i = 1
while i <= len(text):
key_list.append(next(k))
i += 1
num_list = [alph_to_num[s] if s in alph else s for s in text]
num_key_list = [alph_to_num[s] for s in key_list]
for num1, num2 in zip(num_list, num_key_list):
if num1 in num:
encoded_list.append(sum(num1, num2))
else:
encoded_list.append(num1)
encoded_list = [num_to_alph[n % 26 + 1] if n in num else n for n in encoded_list]
encoded_str = ""
for i in encoded_list:
encoded_str += i
print('Your key is: ' + key)
print('The encoded string is: ' + encoded_str)
这里是错误:
line 28, in vigenere_encode
encoded_list.append(sum(num1, num2))
TypeError: 'int' object is not iterable
我找到了一种更优化的方式来编写那段代码,即:
encoded_list = list(map(sum, zip(num_list, num_key_list)))
但是通过这种编写代码的方式,我不确定如何允许对文本中的非字母字符进行编码,并且我想要一种代码格式,允许我编写 decode() 函数而无需改变很多。
我是一个相对初学者。任何帮助表示赞赏。
【问题讨论】: