Home > database >  Learning to use immutable functions on 2d lists
Learning to use immutable functions on 2d lists

Time:09-06

I'm trying to design a function that will sum up every row in a table. There are no headers, only rows. So, if the function was func([[0.2,0.1],[-0.2,0.1],[0.2,-0.1],[-0.2,-0.1]]) it would return [0.3, -0.1, 0.1, -0.3]

So I'm trying to use a nested for loop that will loop over the rows, then the columns, add the values in each row together, and then put that one value in a new list as a new row.

This code below is failing and I've tried numerous iterations of it. I think my problem has something to do with needing to provide an index of where to put the new values but I'm not sure.

numrows=len(table)
numcols=len(table[0])

result= []

for m in range(numrows):
    row=0.00
    for n in range(numcols):
        row=row n
        row.append(table[n][m])
    result.append(row)
return result

CodePudding user response:

To make your approach work, simply replace the lines

row=row n
row.append(table[n][m])

by

row  = table[m][n]

resulting in:

def func(table):
    numrows=len(table)
    numcols=len(table[0])

    result= []

    for m in range(numrows):
        row=0.00
        for n in range(numcols):
            row=row table[m][n]
        result.append(row)
    return result

The issues were that

  • you added the column index instead of the value to the sum,
  • you tried to append to a float and
  • you had the indices switched when accessing the value.

An arguably simpler approach would be the following:

def func(table):
    row_sums = []
    for row in table:
        row_sums.append(sum(row))
    return row_sums

or, an even simpler one:

def func(table):
    return list(map(sum, table))

CodePudding user response:

There are many ways to sum a row-wise list if you look over the SO posts, for example this post. Among them, I would prefer a list comprehension.

alist = [[0.2,0.1],[-0.2,0.1],[0.2,-0.1],[-0.2,-0.1]]

def sum_row_list(a):
    return [sum(i) for i in a]
    

sum_row_list(alist)
[0.30000000000000004, -0.1, 0.1, -0.30000000000000004]
  • Related