Skip to main content
 首页 » 编程设计

python之类型错误 : unsupported operand type(s) for +: 'map' and 'float'

2024年09月07日34zhengyun_ustc

我在 Colaboratory 上练习 tesorflow,我的代码如下。 有一些问题,错误信息是

"TypeError: unsupported operand type(s) for +: 'map' and 'float'"

有人能告诉我这是怎么回事吗?谢谢!

import matplotlib.pyplot as plt 
import numpy as np 
x = np.arange(20) 
y = map(lambda x: x + np.random.randn(1), x) 
a, b = np.polyfit(x, y, 1) 
plt.plot(x, y, 'o', np.arange(20), a*np.arange(20)+b, '-');** 

请您参考如下方法:

'Colaboratory Introduction' 是 Python2 写的,正如@cdarke 所说,map() 在 Python3 中返回一个 map 对象。所以你应该将 map 对象转换为列表。像这样替换代码:

y = list(map(lambda x: x + np.random.randn(1), x))