Sam
Sam

Reputation: 15

Lists and columns in Python

I want to take number inputs from user and add them into a 2 dimensional list and do add the third column together.

Sample Run:

Enter 3 numbers: 1 2 9
Enter 3 numbers: 3 4 9
Enter 3 numbers: 9 1 1
Enter 3 numbers:


1 2 9
3 4 9
9 1 1

column 3 total = 19

This is what I have so far

def main():
  string = input("Enter 3 numbers: ")
  lst = string.split()
  lst = [int(a) for a in lst]
  while string != '':
    string = input("Enter 3 numbers: ")
    lst2 = string.split()
    lst.append([int(a) for a in lst2])
  print(lst)
main()

How do I display my numbers now like in the sample and add only third column together

Upvotes: 0

Views: 54

Answers (1)

tdelaney
tdelaney

Reputation: 77347

You keep overwriting lst. But there is a bigger problem. You need an outer list to hold the user input lists.

def main():
    array = []
    string = input("Enter 3 numbers: ")
    lst = string.split()
    lst = [int(a) for a in lst]
    array.append(lst)
    while string != '':
        string = input("Enter 3 numbers: ")
        lst = string.split()
        array.append([int(a) for a in lst])
    print(array)
main()

Your code would be a bit cleaner if you combined the prompts into a single while loop

def main():
    lst = []
    while True:
        data = input("Enter 3 numbers: ")
        if not data:
            break
        lst.append([int(a) for a in data.split()])
    print lst
    # to get more output....
    for row in lst:
        print('{} {} {}'.format(*row))
    print('column 3 sum is {}'.format(sum(row[2] for row in lst)))
main()

A sample run of the second example

$ python3 x.py
Enter 3 numbers: 1 2 3
Enter 3 numbers: 4 5 6
Enter 3 numbers: 7 8 9
Enter 3 numbers: 
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Upvotes: 3

Related Questions