我有以下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] # => TrueIt 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更多推荐
发布评论