Reputation: 10391
[[2, 3, 4, 6, 9],
[4, 6, 8, 12, 18],
[6, 9, 12, 18, 27],
[8, 12, 16, 24, 36],
[10, 15, 20, 30, 45],
[12, 18, 24, 36, 54],
[14, 21, 28, 42, 63],
[16, 24, 32, 48, 72],
[18, 27, 36, 54, 81],
[20, 30, 40, 60, 90]]
I wanted to sum to value into an array.
Basically, I have this array data, how do I get this output.
The output is something like this
[2+3+4+6+9, 2+3+4+6+18, 2+3+4+6+27, 2+3+4+6+36, 2+3+4+6+45, 2+3+4+6+54, 2+3+4+6+63, 2+3+4+6+71, 2+3+4+6+81, 2+3+4+6+90, 4+3+4+6+9, ...]
I tried something like this and it didn't work
final = [] trans = [*zip(*data)]
k = 0 l = 0
while(k != len(trans) * len(data)): val = 0 m = 0 for d1 in trans:
val = val + d1[m * l]
m = m + 1 l = l + 1 k = k + 1 final.append(val)
Upvotes: 0
Views: 68
Reputation: 2983
In python2:
summed_array = map(sum,array)
for python3:
summed_array = list(map(sum,array))
To do what you have literally requested:
[sum(row[:-1]) + x[-1] for row in array for x in array]
Upvotes: 0
Reputation: 5414
Do you want this?
my_list = [[2, 3, 4, 6, 9],
[4, 6, 8, 12, 18],
[6, 9, 12, 18, 27],
[8, 12, 16, 24, 36],
[10, 15, 20, 30, 45],
[12, 18, 24, 36, 54],
[14, 21, 28, 42, 63],
[16, 24, 32, 48, 72],
[18, 27, 36, 54, 81],
[20, 30, 40, 60, 90]]
sum_list = [sum(i) for i in my_list]
print(sum_list)
Upvotes: 1