【发布时间】:2014-03-15 15:04:12
【问题描述】:
我正在尝试查找数字列表的最大值。
使用 Python 2.7 IDLE,我试过这个:
import numpy
vectors = [[1, 2, 3], [4,5,6]]
numpyFiles = numpy.array(vectors)
maxRawFreq = numpyFiles.max()
有效,maxRawFreq = 6
我尝试使用非常相似的代码,列表更大,并使用 Pydev (Eclipse),但我收到以下错误:
cannot perform reduce with flexible type
这是什么意思? (有关此错误的其他 SO 问题给出了过于具体的解决方案...)。
我的代码:
import numpy
with open(inputFile) as f:
vectors = f.readlines()
vectorLength=len(vectors[0])#number of columns (word vector length)
numpyFiles = numpy.array(vectors)
#both these line gave me the same error:
#maxRawFreq = numpyFiles.max()
maxRawFreq = numpy.max(numpyFiles)
我的inputFile 包含数字,如下所示:
-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0,
+1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6,
【问题讨论】:
-
您正在阅读字符串,而不是数字。您需要相应地转换您的输入。
-
为什么不使用
numpy.loadtxt或numpy.genfromtxt从文件中加载数据?file.readlines只是从文件中返回一个行列表。