[英]python mean of list of lists
我想找到一个包含正数和负数混合列表的所有负数的方法。 我可以找到列表的平均值
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 ]
您可以使用以下内容:
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]
如果sublist
中的所有元素都不小于0
,则列表推导将评估为[]
。 通过包括表达[] or 0
我们处理要评估一个空列表的平均值为您的场景0
。
如果你正在使用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]
纯粹的numpy方式:
In [2]: np.ma.masked_greater(listA,0).mean(1).data
Out[2]: array([-5.5 , -3.5 , -6.33333333, 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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.