2016-08-24 86 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 
相關問題