【问题标题】:Python TypeError: 'int' object is not iterable, trying to append integers to list [closed]Python TypeError:'int'对象不可迭代,试图将整数附加到列表[关闭]
【发布时间】: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() 函数而无需改变很多。

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

【问题讨论】:

标签: python int typeerror


【解决方案1】:

sum 函数接受一个可迭代对象并将可迭代对象内的所有值相加。您尝试将其用作sum(num1, num2),但它不是这样工作的。

如果您只想将两个数字相加,请使用+ 运算符,如:num1 + num2sum() 函数适用于当您已经拥有某种可迭代数据结构中的数字时。

【讨论】:

    【解决方案2】:

    使用encoded_list.append(num1 + num2) 而不是encoded_list.append(sum(num1, num2))

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 2015-04-06
      • 2013-10-31
      • 2016-02-24
      • 1970-01-01
      • 2022-01-20
      • 2014-02-08
      • 2023-03-07
      相关资源
      最近更新 更多