MAAHE
MAAHE

Reputation: 169

Compare one list with several lists

I have 2 lists, one contains 4 lists and the other has the categories. I want to compare the list of categories with every list and sum the values that have the same categories. I tried this way but it returns a list of 8 values instead of 4.

lists=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 3],[ 10, 15, 3, 3, 0, 0,5, 3, 3, 90], [0, 0, 0, 15, 0, 15, 180, 0, 90, 0]]
cat=['alpha','beta','gama','beta','beta','alpha','alpha','beta','gama','beta']
for list in lists:
    for n in range(0,10):
        if cat[n]=='alpha':
            cta= list[n]
            ct1.append((sum([cta])))
        elif cat[n]=='beta':
            ctb = list[n]
            ct2.append((sum([ctb])))
        else:
            ctc = list[n]
            ct3.append((sum([ctc])))
print(ct3)
[0, 0, 0, 0, 3, 3, 0, 90]

Upvotes: 0

Views: 48

Answers (2)

norok2
norok2

Reputation: 26886

You may want to use a dict of list to keep track of stuff instead of list of list:

lists=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 3],[ 10, 15, 3, 3, 0, 0,5, 3, 3, 90], [0, 0, 0, 15, 0, 15, 180, 0, 90, 0]]
cat=['alpha','beta','gama','beta','beta','alpha','alpha','beta','gama','beta']

result = {k: [0] * len(lists) for k in dict.fromkeys(cat).keys()}
for i, l in enumerate(lists):
    for x, c in zip(l, cat):
        result[c][i] += x
print(result)
# {'alpha': [0, 0, 15, 195], 'beta': [0, 3, 111, 15], 'gama': [0, 0, 6, 90]}

Upvotes: 1

deadshot
deadshot

Reputation: 9061

Try this:

for lst in lists:
    cta, ctb, ctc = [], [], []
    for n in range(0,10):
        if cat[n]=='alpha':
            cta.append(lst[n])
        elif cat[n]=='beta':
            ctb.append(lst[n])
        else:
            ctc.append(lst[n])
    ct1.append(sum(cta))
    ct2.append(sum(ctb))
    ct3.append(sum(ctc))

Upvotes: 1

Related Questions