Home > Software engineering >  Adding in a single 2D / Matrix with a string
Adding in a single 2D / Matrix with a string

Time:11-22

How do I add element 1 in all the lists? After that, add element 2? I need to find the percentage of them.

rows = [["SOBs", 60, 80, 70, 75], ["Test1", 60, 50, 60, 65], ["Test2", 40, 30, 40, 45], ["Test3", 45, 90, 80, 85], ["CW", 40, 80, 70, 75]]

I have this:

sum(sum(rows, [2])) - this doesn't work

print(sum(rows[0][1] [1][1])) - also doesn't work

So the for element 1 in it would be 60 60 40 45 40 = 245

Then I take the 245/500*100 = 49%

CodePudding user response:

You can try with list comprehension easily.

element = 1
rows = [["SOBs", 60, 80, 70, 75], ["Test1", 60, 50, 60, 65], ["Test2", 40, 30, 40, 45], ["Test3", 45, 90, 80, 85], ["CW", 40, 80, 70, 75]]
sum_1= sum([rows[i][element] for i in range(len(rows))])
element = 2
sum_2= sum([rows[i][element] for i in range(len(rows))])
print((sum_1*100)/(sum_1 sum_2))

CodePudding user response:

Consider it like a table, and use comprehensions, to summarize columns. Try this

rows = [["SOBs", 60, 80, 70, 75], ["Test1", 60, 50, 60, 65], ["Test2", 40, 30, 40, 45], ["Test3", 45, 90, 80, 85],
        ["CW", 40, 80, 70, 75]]
COL_LENGTH = 4  # set as 4, as you have only 4 colums to evaluate

# Create a list of column values for each column index
selected_cols = [[row[i] for row in rows] for i in range(1, COL_LENGTH)]

# Get sum of every column
sums = [sum(col) for col in selected_cols]

# get avg of every column
avgs = [_sum / 5 for _sum in sums]
  • Related