在查找列表获取一列的总和“类型错误:无法执行降低与灵活型”(Finding Sum of a Col

2019-08-03 07:09发布

所以,我是新来的蟒蛇已经寻找这个答案,但大多数反应是在我的头上。 我有一个这样的名单:

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

我试图分裂清单分成列,并找到数的平均/和/标准偏差。 所以基本上我只是想获得最后到一个数组的形式,我可以使用np.mean,np.sum等用。 这些数据是在一个名为“正确”这里的文件是我到目前为止有:

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)

然后,我得到这个错误:“类型错误:无法执行与灵活型减少:”我已经尝试过吨方式和不断收到错误。 这是另一种方式,我试过,似乎有希望:

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

rightsum=np.sum(TimeSum(right))

但我有同样的错误。 有谁知道如何做到这一点?

Answer 1:

生成一个列表,总结的要素:

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


Answer 2:

应指定(是的,明确的)数据类型,在这种情况下,浮动(或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


文章来源: Finding Sum of a Column in a List Getting “TypeError: cannot perform reduce with flexible type”