2016-08-24 91 views
1

,我有以下的Python 2.7的代码:Jupyter IPython的笔记本电脑和命令行产生不同的结果

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> 
********************************************************************** 

为什么命令行抛出一个错误?有没有更好的方式来构建我的功能?

回答

5

好像你的命令行运行的Python 3.内置map回报在Python 2的列表,而是一个迭代器(一个map对象)在Python 3.要关闭后到一个列表,应用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 
相关问题