Moving from a for loop to a list

I have a program that displays a report and inventory, and I'm just wondering how I could put the following into a list comprehension, not a for-loop ... I kind of like noob at all in this python jargon, but from what I know that everything 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 
+4
source share
2 answers

Your code is essentially equivalent

 TotSize[:] = map(sum, data) 

This will summarize all data , not just the first rows of row and firs col cols. It will also resize TotSize to fit the number of rows of data (assuming TotSize is a list).

I wonder why you go to the list that should store the result. In Python, you usually just return this list:

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

Now it is doubtful whether it is worth defining a function for this at all ...

+7
source

I may 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] 
+6
source

Source: https://habr.com/ru/post/1403780/


All Articles