Jupyter iPython Notebook和命令行产生不同的结果(Jupyter iPython Notebook and Command Line yield different result

系统教程 行业动态 更新时间:2024-06-14 16:52:52
Jupyter iPython Notebook和命令行产生不同的结果(Jupyter iPython Notebook and Command Line yield different results)

我有以下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> **********************************************************************

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

I have the following Python 2.7 code:

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)

When I run it in my browser using iPython notebook, I get the following output:

[4.75, 6.25]

However, when I run the code's file on Command Line (Windows), I get the following error:

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

Why does the command line toss an error? Is there a better way to structure my function?

最满意答案

看起来您的命令行正在运行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

It seems like your command line is running Python 3. The builtin map returns a list in Python 2, but an iterator (a map object) in Python 3. To turn the latter into a list, apply the list constructor to it:

# 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

更多推荐

本文发布于:2023-04-05 12:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/92d342f7981477de027f7e84a65fe50f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令行   Notebook   iPython   Jupyter   results

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!