查找列表中列的总和获取“TypeError:无法使用灵活类型执行reduce”

时间:2012-11-28 23:29:59

标签: python numpy sum typeerror flexible-type

所以我是python的新手并且已经搜索了这个答案,但大多数回复都在我脑海中。我有一个这样的清单:

right point point 1.76999998093
right fear fear 1.62700009346
right sit sit 1.46899986267
right chord chord 1.47900009155
right speed speeed 1.71300005913
right system system 1.69799995422
right hard hard 1.4470000267
right excite excite 2.93799996376
right govern govern 1.85800004005
right record record 1.62400007248

我正在尝试将列表拆分为列,并找到数字的均值/ sum / std dev。所以基本上我只是试图让最后一个数组形式我可以使用np.mean,np.sum等。数据在一个名为'right'的文件中。这是我到目前为止所拥有的:

right=open('right.txt').readlines()
for line in right: 
    l=line.split()
    righttime=l[3]
    print righttime

rightsum=np.sum(righttime)
rightmean=np.mean(righttime)

然后我得到这个错误:“TypeError:无法使用灵活类型执行reduce”我已经尝试了很多方法并且不断出错。这是我尝试的另一种看起来很有希望的方式:

def TimeSum(data):
    for line in data: 
        l=line.split()
        righttime=l[3]
        print righttime
    return righttime

rightsum=np.sum(TimeSum(right))

但我有同样的错误。有谁知道怎么做?

2 个答案:

答案 0 :(得分:7)

生成一个列表并对元素求和:

import numpy as np

right = open('right.txt').readlines()
mylist = []

for line in right:
    l = line.split()  
    mylist.append(float(l[3])) # add to list "mylist"   

rightsum = np.sum(mylist)
print rightsum

或者

mylist = [float(line.split()[3]) for line in right] # generate numbers list
print np.sum(mylist) # sum numbers

答案 1 :(得分:4)

你应该指定(是的,明确地)数据类型,在这种情况下,float(或int,无论如何!):

rightsum  = np.sum(float(righttime))
rightmean = np.mean(float(righttime))

请记住,你必须为numpy.sum()提供一个“类似数组”的结构:

>>>import numpy as np
>>>
>>> mylist = [1, 5, 2]
>>> a = np.asarray(mylist)
>>> a.sum()
8

可替换地:

>>> np.sum([1,5,2])
8