Welcome, guest | Sign In | My Account | Store | Cart

Here is some thing i needed for some kind drill down (olap). It produces tree of grouped items in hierarchy.

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from operator import itemgetter
from itertools import groupby

def groupby2(cols, lst, lev=0):
    if not cols:
        return str(list(lst))
    keyfun = itemgetter(cols[0])
    srted  = sorted(list(lst), key=keyfun)
    output = ""
    for key, iter in groupby(srted, key=keyfun):
        output += "\n"+"   "*lev+"%10s:"%key
        output += groupby2(cols[1:], iter, lev+1)
    return output

Here is some thing i needed for some kind drill down (olap). It produces tree of grouped items in hierarchy. Result is now in string, but should be in some kind of nested list/iterative-objects.

Example: <pre> x = ( (11,23,32, 44) ,(12,21,33, 44) ,(13,22,31, 43) ,(14,27,32, 43) ,(15,27,32, 43) ,(16,27,32, 43) ,(14,25,34, 42) ,(14,25,33, 41) )

print groupby2((3,1,2), x)

output is: 41: 25: 33:[(14, 25, 33, 41)] 42: 25: 34:[(14, 25, 34, 42)] 43: 22: 31:[(13, 22, 31, 43)] 27: 32:[(14, 27, 32, 43), (15, 27, 32, 43), (16, 27, 32, 43)] 44: 21: 33:[(12, 21, 33, 44)] 23: 32:[(11, 23, 32, 44)] </pre>