![](/img/trans.png)
[英]"TypeError: 'function' object is not iterable", why am I getting this error?
[英]I am getting this error message: TypeError: 'function' object is not iterable
我是python的新手。 运行以下代码时出现此错误
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-cdb5a334e110> in <module>
16
17 duplicates_removed = clean_strings
---> 18 duplicates_removed = list(dict.fromkeys(duplicates_removed))
19 print(duplicates_removed)
TypeError: 'function' object is not iterable
有人可以指出我正确的方向吗?
代码
import re
def remove_punctuation(value):
return re.sub('[!#?]', '', value)
clean_ops = [str.strip, remove_punctuation, str.title]
def clean_strings(strings, ops):
result = []
for value in strings:
for function in ops:
value = function(value)
result.append(value)
return result
clean_strings(states_1, clean_ops)
duplicates_removed = clean_strings
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)
错误行是
duplicates_removed = clean_strings
您可能希望将函数的结果存储在duplicates removed
。 为此,您需要执行以下操作:
duplicates_removed = clean_strings(states_1, clean_ops)
注意我之前是如何“合并”这条线的。 在您的原始行中,您实际上将一个函数对象放入duplicates_removed
——它不是函数的结果,而是函数对象本身。
行clean_strings(states_1, clean_ops)
调用函数,但不存储函数结果的任何地方
我也没有看到您在代码中定义states_1
的位置,我猜是之前?
clean_strings(states_1, clean_ops)
调用函数但不将返回值保存到任何变量。
duplicates_removed = clean_strings
只是指向函数而不是调用它,因为它没有 ()
使固定:
duplicates_removed = clean_strings(states_1, clean_ops)
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)
duplicates_removed = clean_strings
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)
您正在将函数clean_strings
的引用传递给dict.fromkeys
! ^^
这个:
duplicates_removed = clean_strings(states_1, clean_ops)
duplicates_removed = list(dict.fromkeys(duplicates_removed))
print(duplicates_removed)
会解决问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.