【发布时间】:2017-12-25 21:56:12
【问题描述】:
我正在做这个代码练习以尝试在 python 中进行函数式编程,但我遇到了 sum()、list() 和 map 对象的问题。我不明白我做错了什么,但 list() 函数似乎与我的地图对象搞砸了。
这是我的代码:
people = [{'name': 'Mary', 'height': 160},
{'name': 'Isla', 'height': 80},
{'name': 'Sam'}]
heights = map(lambda x: x['height'], filter(lambda x: 'height' in x, people))
print(len(list(heights)))
print(sum(list(heights)))
print(len(list(heights)))
average_height = sum(list(heights)) / len(list(heights))
print(average_height)
heights 应该是一个地图对象,包含(或产生)两个现有高度条目的列表:[160, 80]。
打印长度应该是2,两者的和显然应该是240,平均应该是120。
不过,我面临的问题是我收到以下错误消息:
2
0
0
Traceback (most recent call last):
File "C:\Users\Hugo\Dropbox\Programmering\PythonProjekt\exercise2.py", line 12, in <module>
average_height = sum(list(heights)) / len(list(heights))
ZeroDivisionError: division by zero
是的,长度是对的,但是总和是0,第二个长度打印也是0。整个零除错误必须来自那里的某些东西,并且似乎是 list() 函数导致了它。更改打印顺序仍然只能让第一个打印语句正确:
print(sum(list(heights)))
print(len(list(heights)))
print(len(list(heights)))
给予:
240
0
0
Traceback (most recent call last):
File "C:\Users\Hugo\Dropbox\Programmering\PythonProjekt\exercise2.py", line 12, in <module>
average_height = sum(list(heights)) / len(list(heights))
ZeroDivisionError: division by zero
并删除 list() 函数:
print(sum(list(heights)))
print(len(heights))
print(len(list(heights)))
给我:
240
Traceback (most recent call last):
File "C:\Users\Hugo\Dropbox\Programmering\PythonProjekt\exercise2.py", line 9, in <module>
print(len(heights))
TypeError: object of type 'map' has no len()
所以我不知道发生了什么。 list() 函数不应该以任何方式更改地图对象,对吧?它仍然是一个地图对象,但不止一次在它上面调用 list() 似乎会改变它的行为。我很困惑。
【问题讨论】:
-
你想得到什么?平均身高?
-
你用尽了
map迭代器,却没有保存结果...
标签: python python-3.x dictionary sum