清单清单的python平均值 [英] python mean of list of lists
问题描述
我想从包含正负数的列表中找到所有负数的均值.我可以找到列表的平均值为
I want to find the means of all the negative numbers from a list that has a mix of positive and negative numbers. I can find the mean of the lists as
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
I want to create a similar one line code that only takes the mean of the negative numbers in the list. So for example the first element of the new list would be (-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
的情况.
If none of the elements in sublist
are less than 0
, the list comprehension will evaluate to []
. By including the expression [] or 0
we handle your scenario where you want to evaluate the mean of an empty list to be 0
.
这篇关于清单清单的python平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!