Home > Software engineering >  how to sum each array in 3d array
how to sum each array in 3d array

Time:11-01

i have some array

`

 arr_values = [[71, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 78]], 
    [[70, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 79]], 
    [[70, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 80]], 
    [[70, 70, 80, 80, 50, 90, 100, 85, 75], [70, 70, 80, 80, 50, 50, 100, 85, 75], [70, 70, 80, 80, 50, 90, 100, 85, 81]], 
    [[70, 70, 80, 80, 50, 90, 100, 85, 73], [70, 70, 80, 80, 50, 50, 100, 85, 74], [70, 70, 80, 80, 50, 90, 100, 85, 76], [70, 70, 80, 80, 50, 90, 100, 82, 73]]

` i want it become like this

`

[[701] [660] [703]]
[[700] [660] [704]]
[[700] [660] [705]]
[[700] [660] [706]]
[[698] [659] [701] [695]]

`

i have try with this way

`

for values in arr_values:
    for value in range(len(values)):
        a=0
        for a in values[value]:
            a  = a
        print(a)

`

the result is not what i want. how to loop correctly?

`

for values in arr_values:
    for value in range(len(values)):
        a=0
        for a in values[value]:
            a  = a
        print(a)

`

the result is not what i want. how to loop correctly?

CodePudding user response:

If you want to return a list of sums, do it by creating an empty list and then appending each sum iteratively.

arraySums = []
for subArray in arr_values:
    arrays = []
    for array in subArray:
        curSum = 0
        for elem in array:
            curSum  = elem
        arrays.append([curSum])
    arraySums.append(arrays)

Note: arr_values is a tuple of lists
Explanation: Create a list that will hold the result of everything outside of the loop so you can store the results. After that, iterate over the arr_values tuple to get the 2d lists you'll be summing. The inner two for loops are then the sum of a 2 dimensional list, appended to the master list after.

  • Related