我有以下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笔记本在浏览器中运行它时,我得到以下输出:
[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>
**********************************************************************
为什么命令行会抛出错误?有没有更好的方法来构建我的功能?
答案 0 :(得分:5)
看起来您的命令行正在运行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