寻找每一个子表的平均列表中

问题描述:

我试图让列表的每个子列表的平均值: 原来的列表是[5,[1,2],[3,4,5],和想要得到这个清单:[5,1.5,4]。 对于首先计算平均值,我想:寻找每一个子表的平均列表中

l = [5,[1,2],[3,4,5]] 
for x in l: 
    sum(x)/len(x) 

但报道:

Traceback (most recent call last): 
    File "<input>", line 2, in <module> 
    TypeError: 'int' object is not iterable 

我应该怎么得到子表的平均,它在列表中写?

+1

'5'不是列表和'总和(5)'是错误的,如'总和()'预计可迭代。 – AChampion

既然你必须实际总结了一个列表对象,你可以做

l = [5,[1,2],[3,4,5]] 
averages = [] 
for x in l: 
    x_ = x if type(x) is list else [x] 
    #averages += [sum(x_)/float(len(x_))] # I turn the length into a float since you do not mention your version of Python 
    averages.append(sum(x_)/float(len(x_))) 

,输出

[5.0, 1.5, 4.0] 
+0

创建只是让你可以使用'+ ='运营商一个新的列表似乎没有必要,只是'.append()' - 'averages.append(...)' – AChampion

+0

@AChampion。你是对的。这是一种条件反射,因为'+ ='约15%的速度,当一个人不创建列表,慢〜50%*一个反证*。 – Kanak

l中的第一个元素是5这是一个int而不是list因此是错误。

l = [[5],[1,2],[3,4,5]] 
for x in l: 
    sum(x)/len(x) 
+0

谢谢。改性。 – mrinalmech

l = [5,[1,2],[3,4,5]] 
j = [] 
for x in l: 
    if type(x) is list: 
    j.append(sum(list(x))/len(x)) 
    else: 
    j.append(x) 

print(j) 

l = [5,[1,2],[3,4,5]] 
#use the isinstance method to check if the element is a list or not and deal with differently. 
for x in l: 
    print(sum(x)/(len(x)*1.0) if isinstance(x,list) else x) 

5 
1.5 
4.0 

如果你不介意使用另一种包,你可以这样做:

import numpy as np 
#map np.mean method to each sublist of the list to calculate mean. 
map(np.mean,l) 
Out[99]: [5.0, 1.5, 4.0]