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

Zac*_*ach 1 python numpy

如何迭代一组对象以最有效的方式找到它们的平均值?这只使用一个循环(除了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)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?

use*_*424 5

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])
Run Code Online (Sandbox Code Playgroud)

编辑:

要检查是否确实存在任何负面分数,您可以这样:

if np.count_nonzero(scores < 0):
    print 'average negative score: ', np.mean(scores[scores < 0])
Run Code Online (Sandbox Code Playgroud)