在列表中查找列的总和. [英] Finding Sum of a Column in a List Getting "TypeError: cannot perform reduce with flexible type"

查看:80
本文介绍了在列表中查找列的总和.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是python的新手,已经搜索了这个答案,但是大多数答复都超出了我的脑海.我有一个这样的列表:

So I am new to python and have searched for this answer but most responses are over my head. I have a list like this:

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

我正在尝试将列表分成几列,并找到数字的均值/和/std dev.所以基本上我只是想让最后一个进入数组形式,我可以使用np.mean,np.sum等.数据位于名为正确"的文件中,这是我到目前为止所拥有的:

I am trying to split the list into columns and find the mean/sum/std dev of the numbers. So basically i am just trying to get the last into an array form I can use np.mean, np.sum, etc with. The data is in a file called 'right' Here is what I have so far:

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"我尝试了很多方法并不断得到错误.这是我尝试过的另一种看似有希望的方法:

Then I get this error: "TypeError: cannot perform reduce with flexible type" I have tried it tons of ways and keep getting errors. This is another way I tried that seemed promising:

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

rightsum=np.sum(TimeSum(right))

但是我有同样的错误.有人知道该怎么做吗?

But I had the same error. Does anyone know how to do this?

推荐答案

生成列表并将元素求和:

Generate a list and sum the elements:

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

这篇关于在列表中查找列的总和.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆