在列表中查找列的总和得到“TypeError: cannot perform reduce with flexible

Finding Sum of a Column in a List Getting quot;TypeError: cannot perform reduce with flexible typequot;(在列表中查找列的总和得到“TypeError: cannot perform reduce with flexible type)
本文介绍了在列表中查找列的总和得到“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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reading *.mhd/*.raw format in python(在 python 中读取 *.mhd/*.raw 格式)
Count number of cells in the image(计算图像中的单元格数)
How to detect paragraphs in a text document image for a non-consistent text structure in Python OpenCV(如何在 Python OpenCV 中检测文本文档图像中的段落是否存在不一致的文本结构)
How to get the coordinates of the bounding box in YOLO object detection?(YOLO物体检测中如何获取边界框的坐标?)
Divide an image into 5x5 blocks in python and compute histogram for each block(在 python 中将图像划分为 5x5 块并计算每个块的直方图)
Extract cow number from image(从图像中提取奶牛编号)