Skip to main content
 首页 » 编程设计

python之查找对象python中变量的平均值

2025年05月04日19qq号

我如何遍历一组对象以最有效的方式找到它们的平均值?这只使用一个循环(除了 Numpy 中的循环),但我想知道是否有更好的方法。目前,我正在这样做:

scores = [] 
ratings= [] 
negative_scores = [] 
positive_scores = [] 
 
for t in text_collection: 
 scores.append(t.score) 
 ratings.append(t.rating) 
 if t.score < 0: 
    negative_scores.append(t.score) 
 elif t.score > 0: 
    positive_scores.append(t.score) 
 
print "average score:", numpy.mean(scores) 
print "average rating:", numpy.mean(ratings) 
print "average negative score:", numpy.mean(negative_scores) 
print "average positive score:", numpy.mean(positive_scores) 

有更好的方法吗?

请您参考如下方法:

import numpy as np 
scores, ratings = np.array([(t.score, t.rating) for t in text_collection]).T 
 
print 'average score: ', np.mean(scores) 
print 'average rating: ', np.mean(ratings) 
print 'average positive score: ', np.mean(scores[scores > 0]) 
print 'average negative score: ', np.mean(scores[scores < 0]) 

编辑:

要检查是否真的有负分,你可以这样做:

if np.count_nonzero(scores < 0): 
    print 'average negative score: ', np.mean(scores[scores < 0])