使用Python的成对元素 - 计算数组的各个元素的平均值

时间:2015-09-29 06:12:47

标签: python json for-loop multidimensional-array

所以我有一个问题;我正在访问提供以下响应的API:

  

[[" 22014",201939," 0021401229"," APR 15 2015",Team1 vs. Team2"," W&# 34 ;,   19,4,10,0.4,2,4,0.5,0,0,0,2,2,4,7,5,0,2,1,10,14,1],[" 22014&# 34;,201939," 0021401"" APR   13 2015",Team1 vs. Team3"," W",   15,4,13,0.4,2,8,0.5,0,0,0,2,2,4,7,5,0,8,1,12,14,1],[" 22014&# 34;,201939," 0021401192"" APR   11 2015",Team1 vs. Team4"," W",   22,5,10,0.4,2,6,0.5,0,0,0,2,2,4,7,5,0,2,1,8,14,1]

我可以很容易地将16个不同的变量分配给0,然后将它们打印出来,如下例所示:

sum_pts = 0

for n in range(0,len(shot_data)): #range of games; these lengths vary per player
       sum_pts= sum_pts+float(json.dumps(shots_array[n][24]))
print sum_pts/float(len(shots_array))

输出:

>>> 
23.75

但我不想创建16个不同的变量来计算此列表中各个元素的平均值。我正在寻找一种更简单的方法来获得Team1的平均值

我希望输出最终成为,所以我可以将它应用于无限数量的玩家或个人统计数据:

Team1 AVGPTS AVGAST AVGSTL AVGREB...
      23.75  5.3    2.1    3.2

或者可能是:

  Player1 AVGPTS  AVGAST  AVGSTL AVGREB   ...
          23.75    5.3     2.1    3.2 ...

1 个答案:

答案 0 :(得分:0)

要获取每个条目的最后16个条目的平均值,可以使用以下方法,这样就无需为每个列定义多个变量:

data = [
    ["22014",201939,"0021401229","APR 15 2015", "Team1 vs. Team2","W", 19,4,10,0.4,2,4,0.5,0,0,0,2,2,4,7,5,0,2,1,10,14,1],
    ["22014",201939,"0021401","APR 13 2015","Team1 vs. Team3","W", 15,4,13,0.4,2,8,0.5,0,0,0,2,2,4,7,5,0,8,1,12,14,1],
    ["22014",201939,"0021401192","APR 11 2015","Team1 vs. Team4","W", 22,5,10,0.4,2,6,0.5,0,0,0,2,2,4,7,5,0,2,1,8,14,1]]

length = float(len(data))
values = []

for entry in data:
    values.append(entry[6:])

values = zip(*values)
averages = [sum(v) / length for v in values]

for col in averages:
    print "{:.2f} ".format(col),

这会显示:

18.67  4.33  11.00  0.40  2.00  6.00  0.50  0.00  0.00  0.00  2.00  2.00  4.00  7.00  5.00  0.00  4.00  1.00  10.00  14.00  1.00

请注意,您的数据缺少每个Team1 vs Team2之前的开头报价。