1

I'm pretty new to programming, and Python. My textbook has not given me really any information on this and I am stumped now. This is my current code, I need to display the added up columns, and display them like I have the rows.

EDIT:

I had read a few different posts here about using zip() but my book didn't cover it so I couldn't really use it. However this is what I ended up doing:

import random

ROWS = 3
COLS = 3

def main ():
    values = [[0, 0, 0],
             [0, 0, 0],
             [0, 0, 0]] 
for r in range (ROWS):
    for c in range(COLS):
        values[r][c]= random.randint(1,4)

#add up rows
    row0=sum(values[0])
    row1=sum(values[1])
    row2=sum(values[2])

#add up columns
    col0=(values[0][0]+values[1][0]+values[2][0])
    col1=(values[0][1]+values[1][1]+values[2][1])
    col2=(values[0][2]+values[1][2]+values[2][2])

#print results
    print ("List: ")
    print (values)

print ("Total of row 0 is", row0 ) 
print ("Total of row 1 is", row1)
print ("Total of row 2 is", row2 )
print ("Total of column 0 is", col0)
print ("Total of column 1 is", col1)
print ("Total of column 2 is", col2)


main()
2
  • Can you be more specific about your problem? What is your expected output? Commented Nov 21, 2015 at 0:47
  • Sounds like zip() is what you need. It basically swaps columns and rows for you. Commented Nov 21, 2015 at 0:49

2 Answers 2

1

Here I am not using list comprehension or zip as you are new to programming. Hope this code below is pretty simple and self explanatory.

for c in range(COLS):
    sum_col =0  #reset value all row after read
    for r in range (ROWS):
        sum_col+= values[r][c] # sum each element 
    print (sum_col) #finaly print it 
Sign up to request clarification or add additional context in comments.

Comments

0

This line of code will display a list of the columns totaled. Here is a description of the zip function.

print [sum(x) for x in zip(*values)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.