user15457402
user15457402

Reputation: 25

How can I find sum of nested lists in python without using any library?

my list is somethin similar to below: my_list = [[[1,2],[2,3],[1,0]],[[0,1],[1,2]],[[8,9],[2,3],[1,0]]] so, here I am expecting my resulted list is sum of elements divided by all elements from , above list my expected output is: res = [[1.3333,1.6667],[0.5,1],[3.6667,4]]

'''

my_list = [[[1,2],[2,3],[1,0]],[[0,1],[1,2]],[[8,9],[2,3],[1,0]]]
res = [[0,0,0],[0,0,0],[0,0,0]]
for j in range(len(my_list[0])):
    tmp = 0
    for i in range(len(my_list[j])):
        tmp = tmp + my_list[i][j]
    res[j] = tmp / len(my_list)

''' tried above but not working.

Upvotes: 1

Views: 197

Answers (3)

Samwise
Samwise

Reputation: 71542

The functions you'll need to use are len, zip, and sum. I'll break it down step by step to help make it clear what role each individual function plays, with the final line being the complete solution:

>>> my_list = [[[1,2],[2,3],[1,0]],[[0,1],[1,2]],[[8,9],[2,3],[1,0]]]
>>> [len(a) for a in my_list]
[3, 2, 3]
>>> [[x for x in zip(*a)] for a in my_list]
[[(1, 2, 1), (2, 3, 0)], [(0, 1), (1, 2)], [(8, 2, 1), (9, 3, 0)]]
>>> [[sum(x) for x in zip(*a)] for a in my_list]
[[4, 5], [1, 3], [11, 12]]
>>> [[sum(x) / len(a) for x in zip(*a)] for a in my_list]
[[1.3333333333333333, 1.6666666666666667], [0.5, 1.5], [3.6666666666666665, 4.0]]

Upvotes: 1

kcsquared
kcsquared

Reputation: 5409

My interpretation of your question from the various comments is:

Given an m by n (m rows, n columns) matrix, I want a function f that returns the mean of each of the n columns. f should work with any 2D matrix (m and n are unknown). Return the result of applying f to each matrix in my_list.

The following nested loop does this sum over columns:

res = []
for sub_list in my_list:
    res.append([])
    for column in range(len(sub_list[0])):
        col_total = sum(sub_list[i][column] for i in range(len(sub_list)))
        res[-1].append(col_total / len(sub_list))

print(res)

Gives

[[1.3333333333333333, 1.6666666666666667], [0.5, 1.5], [3.6666666666666665, 4.0]]

Upvotes: 0

Luciano Pinheiro
Luciano Pinheiro

Reputation: 95

You have 2 nested lists and you need to do the math the inner one.

res = [[sum(y)/len(y) for y in x] for x in my_list]

In my solution, x is the iteration of the outer list. But it is himself a list. So, we iterate it as y.

The result is

[[1.5, 2.5, 0.5], [0.5, 1.5], [8.5, 2.5, 0.5]]

Upvotes: 1

Related Questions