我试图返回一个除以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
function并返回结果num/2
但是我最后得到了TypeError: 'int' object is not iterable
。
请帮助我了解我在哪里做错了。
谢谢。
您需要调用在函数内部传递的inner
函数,而不是调用正在装饰的函数。另外,您已经将传递的值转换为int
in fnc
,而无需在getEven
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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句