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
Your code is essentially equivalent to
This will sum over all of
data, not only the firstrowrows and the firscolcols. It will also resizeTotSizeto match the number of rowsdatahas (assumingTotSizeis 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:
Now it’s questionable whether it’s worthwhile to define a function for this at all…