'map'类型的对象没有len()包含Float

时间:2019-07-02 09:17:18

标签: python

我正在执行以下代码行。 矢量文件是使用word2vec生成的。

我在此行出现错误:

vector = map(float, fields)
length_of_vectors = len(vector)

错误:

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

我该如何解决此错误?

我尝试过转换

vector = map(float, fields) 

vector = list(map(float, fields))

但出现以下错误:ValueError: could not convert string to float

with io.open(vec_file, 'r', encoding="ISO-8859-1") as f:
    for line in f:
        line = line.strip()
        if line == '':
            continue
        word = line[0:line.index(' ')]
        rest = line[line.index(' ') + 1:]
        fields = rest.split(' ')
        vector = map(float, fields)
        length_of_vectors = len(vector)
        word_vector_dictionary[word] = vector
f.close()

1 个答案:

答案 0 :(得分:0)

这会产生错误,因为您将地图obj赋予len(), 如果您要查找每个元组的长度,请尝试这个

def lenfun(i):
    return len(i)

length_of_vectors = map(lenfun,list_of_tuple)
print(length_of_vectors)

将字符串转换为float时出错:

在给定的代码中'fields'是一个字符串,但在行-> vector = map(float,fields)中,您将字符串'fields'转换为float'fields'(包含数字,字母),字母不能转换为浮动