0

So I have been trying to display four lists in a table format but I am not sure how to go about doing that with large spaces in between the column. This is what I am trying to get:

Number      List1      List2     List3
==========================================
  1          34         16         24
  2          23         27         46
  3          12         17         47
  4          11         43         72
  5          14         22         46

This is the code that I have so far:

list1 = [16, 17, 14, 21, 16, 13, 10, 11, 16, 17]
list2 = [18, 17, 18, 13, 18, 21, 24, 23, 16, 17]
list3 = [0, 0, 2, 0, 0, 0, 0, 0, 2, 0]

print("Number\t\tlist1\t\tlist2\t\tlist3")
print(90*"=")

for x in range(10):
    print(x+1)

for element,element2,element3 in list1,list2,list3:
    print(element,element2,element3)

Only the list of 10 prints, how can I print all the other terms?

1

3 Answers 3

1

Change this:

list1,list2,list3

To this:

zip(list1,list2,list3)
Sign up to request clarification or add additional context in comments.

Comments

1

I used str().center() to format:

list1 = [16, 17, 14, 21, 16, 13, 10, 11, 16, 17]
list2 = [18, 17, 18, 13, 18, 21, 24, 23, 16, 17]
list3 = [0, 0, 2, 0, 0, 0, 0, 0, 2, 0]

print("Number\t\tlist1\t\tlist2\t\tlist3")
print(90*"=")

size_per_col = 5
for i, element1, element2, element3 in zip(range(10), list1, list2, list3):
    print(str(i+1).center(5),
          '\t\t', str(element1).center(size_per_col),
          '\t\t', str(element2).center(size_per_col),
          '\t\t', str(element3).center(size_per_col))

Here https://www.programiz.com/python-programming/methods/string/center is the function center() explained in more detail. format() will work for the problem too.
An alternative solution without using str() is

list1 = [16, 17, 14, 21, 16, 13, 10, 11, 16, 17]
list2 = [18, 17, 18, 13, 18, 21, 24, 23, 16, 17]
list3 = [0, 0, 2, 0, 0, 0, 0, 0, 2, 0]

print("Number\t\tlist1\t\tlist2\t\tlist3")
print(90*"=")

for i, element1, element2, element3 in zip(range(10), list1, list2, list3):
    print('{:^6}\t\t{:^5}\t\t{:^5}\t\t{:^5}'
          .format(i+1, element1, element2, element3))

1 Comment

Is there any way I can do that without using str?
0

You need to zip the list using 'zip' function. I didn't modify much of your code. But, using the below code you can achieve what you want.

list1 = [16, 17, 14, 21, 16, 13, 10, 11, 16, 17]
list2 = [18, 17, 18, 13, 18, 21, 24, 23, 16, 17]
list3 = [0, 0, 2, 0, 0, 0, 0, 0, 2, 0]

print("Number\t\tlist1\t\tlist2\t\tlist3")
print(90*"=")

for number,element,element2,element3 in zip(range(1,len(list3)),list1,list2,list3):
    print(number,"\t\t",element,"\t\t",element2,"\t\t",element3)

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.