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
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…
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With