ABCD
ABCD

Reputation: 9

multiple lists to rows and columns

I've been looking for answers like panda and the sort, but i dont think i'm allowed to use it, so i'm hitting a wall on my assignment, would appreciate it if anyone can help me. also any suggestions on how to make my code be able to handle string values as inputs, and negative inputs? im very new to python.

n = int(input("enter a number:"))
x = range(int(1),n)
list_1 = [x+1 for x in range(n)]
list_1.insert(0,"m")
list_2 = [x+2 for x in range(n)]
list_2.insert(0,"m+1")
list_3 = [(x+1) ** (x+2) for x in range(n)]
list_3.insert(0,"m**(m+1)")
list_of_lists = [list_1, list_2, list_3]

if n>=0:
    for a in zip(*list_of_lists):
        print(*a)


elif n<0:
    print("sorry, only positive integers please")

all it gave was

m m+1 m**(m+1)
1 2 1
2 3 8
3 4 81
4 5 1024
5 6 15625

where I wanted it to be something like

m    m+1    m**(m+1)
1    2      1
2    3      8
3    4      81
4    5      1024
5    6      15625

Upvotes: 1

Views: 63

Answers (2)

solid.py
solid.py

Reputation: 2812

I think this is what you are looking for:

n = int(input("enter a number:"))
# Do the check earlier.
if n>=0:
  x = range(int(1),n)
  list_1 = [x+1 for x in range(n)]
  list_1.insert(0,"m")
  list_2 = [x+2 for x in range(n)]
  list_2.insert(0,"m+1")
  list_3 = [(x+1) ** (x+2) for x in range(n)]
  list_3.insert(0,"m**(m+1)")
  list_of_lists = [list_1, list_2, list_3]

  # Print here, use a sep(arator) of \t -> tab
  # instead of the default one which is space.
  for a in zip(*list_of_lists):
        print(*a, sep = '\t', end = '\n')

elif n<0:
    print("sorry, only positive integers please")

This prints in console:

enter a number: 5
m   m+1 m**(m+1)
1   2   1
2   3   8
3   4   81
4   5   1024
5   6   15625

Upvotes: 0

Alex Sveshnikov
Alex Sveshnikov

Reputation: 4339

Instead of

print(*a)

use

print("{:<8} {:<8} {:<8}".format(*a))

It places each element in 8-character width column and left-adjust them (because of < in front of 8).

Upvotes: 1

Related Questions