Reputation: 1
I created a large array that is similar to this:
data = [ [1,2,3], [0,1,3],[1,5,3]]
How can I make it so my new array sums up each individual array as shown?
data = [ [6],[4],[9] ]
Upvotes: 0
Views: 31
Reputation: 8057
List comprehensions are good for this:
[[sum(x)] for x in data] # [[6], [4], [9]]
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
You're wanting to make a new list where each element is the result of some operations (a sum in this case) applied to each member of another sequence or iterable (your list of lists).
Upvotes: 2
Reputation: 47
This works.
a = [ [1,2,3], [0,1,3],[1,5,3]]
b = []
for i in a:
sum = 0
for j in i:
sum+=j
b.append([sum])
print(b)
Upvotes: 1