当查找最大值时,Python错误“cannot perform reduce with flexible type”

2024-09-30 03:22:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出一个数字列表的最大值。在

使用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问题给出了太具体的解决方案…)。在

我的代码:

^{pr2}$

我的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,

Tags: 代码importnumpy列表错误数字arraymax
2条回答
In [81]: data=numpy.genfromtxt(inputFile, delimiter=',')[:, :-1]

In [82]: data
Out[82]: 
array([[-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.]])

如果您想自己解析它:

^{pr2}$

问题在于:

with open(inputFile) as f:
  vectors = f.readlines()

如果文件如下所示:

^{pr2}$

你的向量如下所示: ['a, b, c, d\n', '1, 1, 3, 4\n', '2, 3, 5, 6\n', ...] 然后需要将这些字符串转换为数值。在

尝试以正确的方式读取csv(或者您的输入文件是什么)

相关问题 更多 >

    热门问题