python-多维列表并创建一个dict并计算其平均值

时间:2014-02-10 10:58:21

标签: python arrays dictionary

我有一个清单

像这样

myList = [ ['jan','423','523','645'],
            ['jan','654','754','765'],
            ['nov','756','087','140'],
            ['nov','233','123','032']
            ['apr','654','786','223'] ]

我想通过列表并根据第一个elemnt(即'jan','nov')将所有子列表(myList)分组。 其关键也是列表的第一个元素。

myDict = {'jan':[ 
                ['423','654'], # average
                ['523','754'], # average
                ['645','765'] # average
                ],
        'nov':[ 
                ['756','233'], # average
                ['087','123'], # average
                ['140','032'] # average
                ],
        'apr':[ 
                ['654'], # average
                ['786'], # average
                ['223'] # average
                ],
        }

然后我想计算该字典的所有列表元素的平均值。

像这样

myDict = {'jan':[ 
                ['423','654'], # average
                ['523','754'], # average
                ['645','765'] # average
                ],.....

注意:这只是示例数据,我在子列表中有数百个元素 [[34,654,756,8,675,75,64,3,45,...,N],[子列表-第2..N],[子列表-3 .... N]] 但每个子列表的长度是固定的。

mycode的:

myList
db = {}    
for i in myList:

    human = i[0]    
    newlist = i[1:]

    # print pprint(db)
    columns = []
    counter = 0

    while counter < len(newlist):
        if db.has_key(human):
            db[human][counter].append(newlist[counter])
        else:
            columns.append([newlist[counter]])
            db[human] = columns
        counter += 1

当我只有2件物品时,下面列出的代码运作良好。

human = i[0]
col_1 = i[1]
col_2 = i[2]

if db.has_key(human):
    db[human][0].append(col_1)
    db[human][1].append(col_2)
else:
    db[human] = [ [col_1], [col_2] ]

print
pprint(db)
print columns

# function to calculate average
def getAvg(column):
    total = 0
    average = 0
    for val in column:
        length = len(column)
        int_val = float(val)
        total += int_val
        average = total / length
    return average

col_1_avg = getAvg(col_1)
col_2_avg = getAvg(col_2)

result = human + ',' + str(getAvg(col_1)) + ',' +str(getAvg(col_2))

1 个答案:

答案 0 :(得分:0)

  myList = [['jan','423','523','645'],
            ['jan','654','754','765'],
                ['nov','756','087','140'],
                ['nov','233','123','032'],
                ['apr','654','786','223']]

 from collections import defaultdict
 mydict = defaultdict(list)
 for each in myList:
     mydict[each[0]].append(each[1:])
 datadict = {}
 for each in mydict:
     datadict[each] = zip(*mydict[each])
 print datadict