python - Python:装饰器+列表理解-TypeError:'int'对象不可迭代
问题描述
我试图返回一个除以 2 的列表以获得列表中的偶数。我正在尝试使用装饰器执行此操作,但出现错误TypeError: 'int' object is not iterable
我的代码是
def getEven(fnc):
def inner(list_of_val):
return [ devideBy2(int(value)) for value in list_of_val ]
return inner
@getEven
def devideBy2(num):
return int(num)/2
list_of_num = [ 1, 2, 3, 4, 5]
print(devideBy2(list_of_num))
当我迭代list_of_num
它打印每个数字时,我的想法是,现在这个每个数字将传递一个参数给devideBy2
函数并返回结果num/2
但我结束了TypeError: 'int' object is not iterable
。
请帮助我了解我在哪里做错了。
谢谢你。
解决方案
您需要调用您在函数内部传递的inner
函数,而不是调用您正在装饰的函数。此外,您已经将传递的值转换为int
in fnc
,无需再次执行 ingetEven
def getEven(fnc):
def inner(list_of_val):
# Call fnc here instead of devideBy2
return [ fnc(value) for value in list_of_val ]
return inner
@getEven
def devideBy2(num):
return int(num)/2
list_of_num = [ 1, 2, 3, 4, 5]
print(devideBy2(list_of_num))
推荐阅读
- python - 在 Python 中,使用从文件中提取的值列表,如何找到浮点值列的总和?
- javascript - 如何在 Ajax 中调用 Express 路由?
- python-3.x - 如何用火花运行matlab函数?
- r - CentOS 上缺少软件包“udunits2”
- scala - 在 sbt-scalajs-crossproject 插件中,您如何为 JS 和 JVM 编译目标指定一个主类?
- javascript - 我需要帮助为我的一种方法修复单元测试
- r - R:带有交互 IV 的 felm 函数
- swift - swift repl 在 linux 的 windows 子系统中不起作用
- git - 在发布分支中查找先前的合并提交
- reactjs - 了解动画和键盘事件