2016-03-01 225 views
3

我想从正数和负数混合的列表中找到所有负数的均值。我能找到名单的平均值作为python的列表名单列表

import numpy as np 

listA = [ [2,3,-7,-4] , [-2,3,4,-5] , [-5,-6,-8,2] , [9,5,13,2] ] 
listofmeans = [np.mean(i) for i in listA ] 

我想创建一个类似的一行代码,只需要在列表中的负数的平均值。因此,例如新列表的第一个元素是(-7 + -4)/ 2 = -5.5

我的完整列表是:

listofnegativemeans = [ -5.5, -3.5, -6.333333, 0 ] 
+1

最后名单的平均值不为0,这是不确定的。 – wim

回答

3

您可以使用下列内容:

listA = [[2,3,-7,-4], [-2,3,4,-5], [-5,-6,-8,2], [9,5,13,2]] 
means = [np.mean([el for el in sublist if el < 0] or 0) for sublist in listA] 
print(means) 

输出

[-5.5, -3.5, -6.3333, 0.0] 

如果没有元件的我n sublist小于0,列表理解将评估为[]。通过包含表达式[] or 0我们处理您想要评估空列表的平均值为0的场景。

+1

当没有元素不正确时返回零。 – purpletentacle

+0

@ mtk99这是OP要求的!它不直观,但它是正确的 – gtlambert

0

这将是这样的:

listA = np.array([ [2,3,-7,-4] , [-2,3,4,-5] , [-5,-6,-8,2] , [9,5,13,2] ]) 

listofnegativemeans = [np.mean(i[i<0]) for i in listA ] 

输出:

[-5.5, -3.5, -6.333333333333333, nan] 

零是误导性的,我肯定更喜欢nan如果你没有那些负面的任何元素。

2

如果你使用numpy,你应该争取numpythonic代码而不是回落到Python逻辑。这意味着使用numpy的ndarray数据结构,以及数组的常用索引风格,而不是Python循环。

对于惯用手段:

>>> listA 
[[2, 3, -7, -4], [-2, 3, 4, -5], [-5, -6, -8, 2], [9, 5, 13, 2]] 
>>> A = np.array(listA) 
>>> np.mean(A, axis=1) 
array([-1.5 , 0. , -4.25, 7.25]) 

负数表示:

>>> [np.mean(row[row<0]) for row in A] 
[-5.5, -3.5, -6.333333333333333, nan] 
1

纯numpy的方式:

In [2]: np.ma.masked_greater(listA,0).mean(1).data 
Out[2]: array([-5.5  , -3.5  , -6.33333333, 0.  ]) 
+0

是的,我认为这是最好的方法。忘记了蒙面阵列! – wim