5

所以我是 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

我正在尝试将列表拆分为列并找到数字的均值/总和/标准差。所以基本上我只是想把最后一个变成一个数组形式,我可以使用 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)

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

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

rightsum=np.sum(TimeSum(right))

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

4

2 回答 2

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
于 2012-11-29T00:17:28.893 回答
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
于 2012-11-28T23:49:53.423 回答