Python TypeError:'int'对象不可迭代,尝试将整数追加到列表中

时间:2018-06-11 20:04:41

标签: python int typeerror

任何人都可以帮我解决这个错误吗?

这是加密/解密游戏的代码。

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()函数的代码格式无需改变很多。

我是一个相对初学者。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

branch_id函数采用iterable并对可迭代内的所有值求和。您试图将其用作sum,而不是它的工作方式。

如果您只想将两个数字加在一起,请使用sum(num1, num2)运算符,如:+; num1 + num2函数用于在某种可迭代数据结构中已有数字时。

答案 1 :(得分:0)

使用encoded_list.append(num1 + num2)代替encoded_list.append(sum(num1, num2))