Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jupyter iPython笔记本和命令行产生不同的结果_Python - Fatal编程技术网

Jupyter iPython笔记本和命令行产生不同的结果

Jupyter iPython笔记本和命令行产生不同的结果,python,Python,我有以下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: >>> ave

我有以下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]
但是,在命令行窗口上运行代码文件时,出现以下错误:

>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。内置映射在Python2中返回一个列表,但在Python3中,迭代器返回一个映射对象。要将后者转换为列表,请对其应用列表构造函数:

# 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

看起来您的命令行正在运行Python3。内置映射在Python2中返回一个列表,但在Python3中,迭代器返回一个映射对象。要将后者转换为列表,请对其应用列表构造函数:

# 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