我收到此错误消息: TypeError: 'function' object is not

我是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)


慕的地8271018
浏览 163回答 3
3回答

慕田峪4524236

错误行是duplicates_removed&nbsp;=&nbsp;clean_strings您可能希望将函数的结果存储在duplicates removed.&nbsp;为此,您需要执行以下操作:duplicates_removed&nbsp;=&nbsp;clean_strings(states_1,&nbsp;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)

holdtom

duplicates_removed = clean_stringsduplicates_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)就可以解决问题了:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python