关于在 python 3.6 中导入 reduce() 方法

About reduce() method importing in python 3.6

正在导入

    import reduce from functools

创建字符串列表:stark

    stark = ['robb', 'sansa', 'arya', 'brandon', 'rickon']

使用 reduce() 在 stark 上应用 lambda 函数:结果

    result = reduce(lambda item1 , item2 : item1 + item2 ,stark)

打印结果

    print(result)

在这个简单的代码中,我在第 2 行收到语法错误 - import reduce from functools 此外,我还尝试为 reduce() 导入 functools 但没有成功。

如问题评论中所述,要从 module 导入 class/function,语法为:

from module import class/function

所以在你的情况下,你应该使用:

from functools import reduce

祝您编程愉快! :)