BGDev
BGDev

Reputation: 135

Python, Error or incorrect output in function sum over lists of lists

Receiving errors when creating a function to sum a values in a List of Lists

Example: Seeking to generate this type of output

listtest = [1,2,3,4,5,6]
print(sum(listtest)) # output is 21

But for a list of lists

listsample = [[1,2,3,4,5],[1,2,5,4,6,7],[7,8,9,5,6]]
# Desired_output= [15,25,35]

I know this can be done and works

listsample = [[1,2,3,4,5],[1,2,5,4,6,7],[7,8,9,5,6]]
result = list(map(sum,listsample))
print(result)
# Desired_output= [15,25,35]

How is one to manipulate the sum function to allow it to pass without error within a function?

I've commented on the methods attempted and the outcomes, please un-comment to test or run code.

listsample = [[1,2,3,4,5],[1,2,5,4,6,7],[7,8,9,5,6]]
import itertools as itr
def sumrows(ls):
    for i in ls:
        for subls in range(0,len(i)):
            # opt = 0
            # opt = opt + i[subls] # -->> generates output of None
            # return sum(subls for i in range(0,len(i))) # -->> generates unusual output of 0 - I'm not sure how this value is arrived at
            # return list(map(sum, subls)) # -->> generates error " 'int' object is not iterable "
            # return list(i(sum((subls)))) # -->> generates error " 'int' object is not iterable "
            # return list(i(sum(itr.chain.from_iterable(subls))))  # -->> generates error " 'int' object is not iterable "

print("output", sumrows(listsample))

Upvotes: 1

Views: 449

Answers (1)

AdamGold
AdamGold

Reputation: 5071

It looks like you are trying to create a new sum function to accept a list of lists:

def new_sum(l):
    return [sum(e) for e in l]

listsample = [[1,2,3,4,5],[1,2,5,4,6,7],[7,8,9,5,6]]
print(new_sum(listsample))
# outputs [15, 25, 35]

Upvotes: 2

Related Questions