So, as stated, it is a 2D list. 6 columns (6 random numbers) within 7 rows. The formatting for the out put should look like this: http://i.stack.imgur.com/hwnHi.png
what I have for my code is this:
print (" ", 1 , " ", 2, " ",3, " ",4, " ",5, " ",6)
print ()
for i in range(7):
print (i+1, *Pizza[i], sep=" ")
print ("To", *sales_of_hours, sep=" ")
Pizza is my 2D list, and sales_of_hours is a list of the totals for each column, and I have another list named sales_of_day for the totals of each row, but when I try to add that to the loop like this:
for i in range(7):
print (i+1, *Pizza[i], sep=" ", *sales_of_day[i])
I get a syntax error. What am I doing wrong?
Most probably, sales_of_day
is a one dimensional list, if so, you cannot unpack sales_of_day[i]
, since that would most probably be a number.
Also, you do not need to manually give the spaces and all, you can use right asligment of str.format()
, to achieve similar result , code -
print(' '*6,end='')
for i in range(6):
print('{:>6}'.format(i+1),end="")
print('{:>6}'.format('Total'))
for i in range(7):
print('{:>6}'.format(i+1),end='')
for j in range(6):
print('{:>6}'.format(pizza[i][j]),end="")
print('{:>6}'.format(sales_of_day[i]))
print('{:>6}'.format('To'),end='')
for i in range(6):
print('{:>6}'.format(sales_of_hours[i]),end='')
print()
The format {:>6}
forces the string to be right-aligned within the available space (this is the default for numbers).
Demo -
import random
pizza = [[random.randint(1,9) for j in range(6)] for i in range(7)]
print(' '*5,end='')
for i in range(6):
print('{:>5}'.format(i+1),end="")
print('{:>5}'.format('Total'))
for i in range(7):
print('{:>5}'.format(i+1),end='')
for j in range(6):
print('{:>5}'.format(pizza[i][j]),end="")
print('{:>5}'.format(sum(pizza[i])))
print('{:>5}'.format('To'),end='')
for i in range(6):
print('{:>5}'.format(random.randint(10,50)),end='')
print()
Output -
> python a.py
1 2 3 4 5 6Total
1 4 6 6 2 6 9 33
2 2 4 6 1 3 7 23
3 1 4 3 5 7 1 21
4 5 5 2 7 2 2 23
5 3 1 6 8 1 7 26
6 6 2 3 3 6 8 28
7 3 9 6 6 4 4 32
To 45 45 25 40 30 34
after * it must be a sequence, so try to remove * from sales_of_day
space = " "*5
for i in range(7):
print (i+1, *Pizza[i], sep=space,end=space)
print (sales_of_day[i])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.