python:' map'对象不可订阅

时间:2017-10-11 02:17:21

标签: python dictionary

我有这段代码:

    def substract_mean(self, group_point):
    for i, a in enumerate(group_point):
        group_point[i] = group_point[i] - self.mean_global[i]
    return group_point

我收到以下错误消息:

  

group_point [i] = group_point [i] - self.mean_global [i]

     

TypeError:' map'对象不可订阅

2 个答案:

答案 0 :(得分:0)

如果您使用的是Python 3,则map()函数已从Python 2更改。 map()在Python 3中返回一个迭代器,所以如果你想将它转换成一个可订阅的列表,你应该在list()函数中包含你的map()变量。

e.g。列表(地图(...))

来源:https://docs.python.org/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists

答案 1 :(得分:0)

def square(n):
    return n*n


class MeanClass:
    mean_global = [10, 20, 30, 40]

    def substract_mean(self, group_point):
        for i, a in enumerate(group_point):
            group_point[i] = group_point[i] - self.mean_global[i]
        return group_point


c = MeanClass()
l = [1,2,3,4]
m = map(square,l)
print('works on a list object', c.substract_mean(l))
print('works on map object converted to a list',c.substract_mean(list(m)))
print('fails on a map object',c.substract_mean(m))