TypeError: 'int' object is not iterable错误:列表添加操作异常原因求解
TypeError: 'int' object is not iterable错误原因及修复
错误触发点
代码里的pos_of_operators += num这一行直接导致了错误。另外all_numbers += x虽然没报错,但写法也不规范。
为什么会报错?
Python中,给列表使用+=操作符时,要求右边的对象必须是可迭代类型(比如列表、字符串、元组等),Python会把可迭代对象里的元素逐个添加到列表中。
- 对于
pos_of_operators += num:num是循环中拿到的索引整数,整数不属于可迭代类型,Python没法对它进行迭代操作,所以抛出TypeError: 'int' object is not iterable。 - 对于
all_numbers += x:x是字符串的单个字符(比如"1"),字符串属于可迭代类型,所以这行能运行,但这是利用了字符串的特性,并不是添加单个元素的标准写法,容易造成误解。
正确的写法
要给列表添加单个元素,应该用列表的append()方法,修改后的代码如下:
def calculate(string: str): allowed_symboles = "1234567890+-*$" symbole_sum = len(string) symbole_sum0 = 0 for symbole in string: for lol in allowed_symboles: if symbole == lol: symbole_sum0 += 1 if symbole_sum != symbole_sum0: return "400: Bad request" all_numbers = [] pos_of_operators = [] for x, num in zip(string, range(0, len(string))): if x != "+" and x != "-" and x != "*" and x != "$": all_numbers.append(x) # 用append添加单个字符 else: pos_of_operators.append(num) # 用append添加单个索引整数 print(all_numbers, pos_of_operators) calculate("1231241+4234")
运行修改后的代码,就能正常输出:['1', '2', '3', '1', '2', '4', '1', '4', '2', '3', '4'] [7],符合存储数字字符和符号索引的需求。
内容的提问来源于stack exchange,提问作者Igor czerbniak
相关产品推荐
相关产品推荐

