在列表中查找列的总和得到“TypeError: cannot perf

时间:2023-02-07
本文介绍了在列表中查找列的总和得到“TypeError: cannot perform reduce with flexible type"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在尝试将列表拆分为列并找到数字的均值/总和/标准差.所以基本上我只是想把最后一个变成一个数组形式,我可以使用 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: cannot perform reduce with flexible type"我已经尝试了很多方法并且不断出错.这是我尝试过的另一种看起来很有希望的方法:

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

这篇关于在列表中查找列的总和得到“TypeError: cannot perform reduce with flexible type"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:使用 Python 对包含“无"的列表求和 下一篇:Python Pandas:计算每行数据帧中特定值的频率?

相关文章

最新文章