我有以下 Python 2.7 代码:
def average_rows2(mat):
'''
INPUT: 2 dimensional list of integers (matrix)
OUTPUT: list of floats
Use map to take the average of each row in the matrix and
return it as a list.
Example:
>>> average_rows2([[4, 5, 2, 8], [3, 9, 6, 7]])
[4.75, 6.25]
'''
return map(lambda x: sum(x)/float(len(x)), mat)
当我使用 iPython notebook 在浏览器中运行它时,我得到以下输出:
[4.75, 6.25]
但是,当我在命令行 (Windows) 上运行代码文件时,出现以下错误:
>python -m doctest Delete.py
**********************************************************************
File "C:\Delete.py", line 10, in Delete.average_rows2
Failed example:
average_rows2([[4, 5, 2, 8], [3, 9, 6, 7]])
Expected:
[4.75, 6.25]
Got:
<map object at 0x00000228FE78A898>
**********************************************************************
为什么命令行会抛出错误?有没有更好的方法来构建我的功能?
请您参考如下方法:
您的命令行似乎正在运行 Python 3。内置 map 在 Python 2 中返回一个列表,但在 Python 3 中返回一个迭代器(一个 map 对象)。要将后者转换为列表,请对其应用 list 构造函数:
# Python 2
average_rows2([[4, 5, 2, 8], [3, 9, 6, 7]]) == [4.75, 6.25]
# => True
# Python 3
list(average_rows2([[4, 5, 2, 8], [3, 9, 6, 7]])) == [4.75, 6.25]
# => True
