嵌套列表中的sum值为python

时间:2017-06-01 08:52:16

标签: python list average

我有一个清单:

l = [['a', 10, 30], ['b', 34, 89], ['c', 40, 60],['d',30,20]]

其中每个子列表中的第一个项目是名称,其他两个数字是标记(sub1和sub2)

嵌套列表可以是动态的,即嵌套列表的数量可以根据功能而改变。

我正在寻找的是

average of subj 1 i.e (10+34+40+30)/4 and 
similarly sub2 (30+89+60+20)/4

also average marks of a: (10+30)/2
average marks of b: (34+89)/2  and so on.

我试过了:

c = 0
for i in range(0,len(list_marks1)):
    c += list_marks1[i][1]
sub_1avg = float(c)/len(list_marks1)
d = 0
for i in range(0,len(list_marks1)):
    d += list_marks1[i][2]
sub_2avg = float(d)/len(list_marks1)

但这不正确。

有没有最佳方法可以做到这一点?由于我的嵌套列表中的主题数也可以更改。

3 个答案:

答案 0 :(得分:4)

您可以使用sum和生成器表达式:

>>> l= [['a', 10, 30], ['b', 34, 89], ['c', 40, 60],['d',30,20]]
>>> length = float(len(l))  # in Python 3 you don't need the "float"
>>> sum(subl[1] for subl in l) / length 
28.5
>>> sum(subl[2] for subl in l) / length
49.75

甚至可以在列表理解中做到这一点:

>>> [sum(subl[subj] for subl in l) / length for subj in range(1, 3)]
[28.5, 49.75]

同样对于一个子列表的平均值:

>>> length = float(len(l[0])) - 1
>>> [sum(subl[1:]) / length for subl in l]
[20.0, 61.5, 50.0, 25.0]

如果你有python 3.4或更新版本,你可以用statistics.mean替换sum / length

>>> from statistics import mean
>>> [mean(subl[subj] for subl in l) for subj in range(1, 3)]  
[28.5, 49.75]

>>> [mean(subl[1:]) for subl in l]
[20, 61.5, 50, 25]

你问过最好的方法,所以我可能应该提到有专门用于表格数据的软件包。例如,如果您使用pandasDataFramemean就更容易了:

>>> import pandas as pd

>>> df = pd.DataFrame(l, columns=['name', 'x', 'y']) 
>>> df[['x', 'y']].mean(axis=0)
x    28.50
y    49.75
dtype: float64

>>> df[['x', 'y']].mean(axis=1)
0    20.0
1    61.5
2    50.0
3    25.0
dtype: float64

答案 1 :(得分:0)

一种非常方法:

l= [['a', 10, 30], ['b', 34, 89], ['c', 40, 60],['d',30,20]]
map(lambda x: sum(x)/float(len(x)), zip(*l)[1:])
[28.5, 49.75]

这种方式适用于任何子列表长度

答案 2 :(得分:0)

l= [['a', 10, 30], ['b', 34, 89], ['c', 40, 60],['d',30,20]]
sub1_avg =  sum(n for _,n, _ in l)/float(len(l))
sub2_avg =  sum(n for _,_, n in l)/float(len(l))
student_avgs = [{x[0]: sum(x[1:])//float((len(x)-1))} for x in l]
print "Sub1 avg - {}\nSub2 avg - {}\nstudent avg - {}".format(sub1_avg, sub2_avg, student_avgs)

示例输出

Sub1 avg - 28.5
Sub2 avg - 49.75
student avg - [{'a': 20.0}, {'b': 61.0}, {'c': 50.0}, {'d': 25.0}]