使用zip()与列表推导式计算利润时遇TypeError报错的解决方法
问题:结合zip()用列表推导式生成利润列表
给定数据:
revenue = [30000, 50000, 70000, 90000] cost = [10000, 15000, 20000, 30000]
已通过for循环实现需求,代码如下:
new_list = [] for revenue, cost in zip(revenue, cost): profit = revenue - cost new_list.append(profit) new_list
输出结果:[20000, 35000, 50000, 60000]
尝试用列表推导式实现时编写了以下代码,出现报错:
zipped_list = list(zip(revenue, cost)) [revenue - cost for num1, num2 in zipped_list]
报错信息:TypeError: 'int' object is not iterable
错误原因
- 前面的for循环里,你用
revenue和cost作为循环变量,已经把原来的列表变量覆盖成了单个整数,导致后续代码里这两个变量是int类型,无法参与列表推导式的运算。 - 就算没覆盖变量,你也应该用列表推导式循环里的
num1和num2来计算利润,而不是直接用原来的列表变量。
另外,其实不需要提前把zip结果转成list,直接在推导式里用zip(revenue, cost)即可。
正确代码
写法一(直接在推导式中使用zip)
profit_list = [rev - cst for rev, cst in zip(revenue, cost)] print(profit_list)
输出:[20000, 35000, 50000, 60000]
写法二(保留zipped_list的情况)
注意使用和全局变量不冲突的循环变量名:
zipped_list = list(zip(revenue, cost)) profit_list = [num1 - num2 for num1, num2 in zipped_list] print(profit_list)
内容的提问来源于stack exchange,提问作者Young
相关产品推荐
相关产品推荐

