我有以下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)
Run Code Online (Sandbox Code Playgroud)
当我使用iPython笔记本在浏览器中运行它时,我得到以下输出:
[4.75, 6.25]
Run Code Online (Sandbox Code Playgroud)
但是,当我在命令行(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>
**********************************************************************
Run Code Online (Sandbox Code Playgroud)
为什么命令行会抛出错误?有没有更好的方法来构建我的功能?
看起来你的命令行正在运行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
Run Code Online (Sandbox Code Playgroud)