网站首页 文章专栏 map在python2和python3之间的兼容性
map在python2和python3之间的兼容性
创建于:2018-04-11 16:00:00 更新于:2024-03-29 11:28:13 羽瀚尘 1035
python python,map

问题

在python2中的代码使用了map重复使用lambda函数,又对输出用len()取出长度

# map function
Y_train = to_onehot(map(lambda x: mods.index(lbl[x][0]), train_idx))

# use len() in child function
def to_onehot(yy):
    yy1 = np.zeros([len(yy), max(yy)+1])
    yy1[np.arange(len(yy)),yy] = 1
    return yy1

报的错误为:

TypeError: object of type 'map' has no len()

解决

在map外面再加一层list

Y_test = to_onehot(list(map(lambda x: mods.index(lbl[x][0]), test_idx)))

Reference: 1. TypeError: object of type 'map' has no len() Python3 https://stackoverflow.com/questions/41903852/typeerror-object-of-type-map-has-no-len-python3