Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Going from a for loop to a list comprehension

I have a program that displays and inventory report and i was just wondering how I could put the following into a list comprehension instead of a for-loop...I'm kind of a noob at all this python jargon but from what i know is that anything that is in the form of a for-loop can also be expressed as a list comprehension....ANY help would be appreciated

def rowSum(TotSize,data,row,col):
    """Calculates the sum of each row in a given 2 dimensional list and stores
it into a given one dimensional list"""
    for i in range(row):
        sum = 0
        for j in range(col):
            sum += data[i][j]
        TotSize[i] = sum
like image 286
koala421 Avatar asked Dec 13 '22 03:12

koala421


2 Answers

Your code is essentially equivalent to

TotSize[:] = map(sum, data)

This will sum over all of data, not only the first row rows and the firs col cols. It will also resize TotSize to match the number of rows data has (assuming TotSize is a list).

I wonder why you are passing in the list that should store the result. In Python, you'd usually simply return that list:

def row_sums(data):
    return map(sum, data)

Now it's questionable whether it's worthwhile to define a function for this at all…

like image 97
Sven Marnach Avatar answered Dec 26 '22 18:12

Sven Marnach


I might have misunderstood your question, but are you asking for something like this?

>>> testdata = [[5, 6, 8], [], range(8), [42]]
>>> ToTSize = [sum(row) for row in testdata]
>>> ToTSize
[19, 0, 28, 42]
like image 38
Nolen Royalty Avatar answered Dec 26 '22 19:12

Nolen Royalty