user3260982
user3260982

Reputation:

How to print a list tuples in a nice format?

I am trying to print out a list of tuples in a nice format that will have student name, exam score1, exam score2, and exam score average. I have already calculated the averages and everything is stored in a list of tuples. But, my problem is to format the information and print out nicely. Here are my codes:

#asks the user to enter the input file name
file_name=input('Enter the input file name: ')

#open input file for reading purpose
input_file = open(file_name,'r')
i=0

input_list=[]
#for loop splits each line of the input file and creates a list
for line in input_file:
   line_list=line.split()
   #a new list is created 
   input_list.append(line_list)

#appends the average of two exam
#scores to each element of the input_list
for line in range(len(input_list)):
   avg=(float((int(input_list[i][2])+int(input_list[i][3]))/2))
   input_list[i].append(avg)
   i+=1
#trning elements of the input_list into
#tuples and appending them to a new_input_list   
new_input_list=[]
for element in input_list:
   element=tuple(element)
   new_input_list.append(element)

exam1_total=0
exam2_total=0
#calculating total exam scores of the entire list
for i in range(len(new_input_list)):
   exam1_total+=int(new_input_list[i][2])
   exam2_total+=int(new_input_list[i][3])   
   i+=1


exam1_avg=float(exam1_total/i)
exam2_avg=float(exam2_total/i)
print(exam1_avg)
print(exam2_avg)
new_input_list=sorted(new_input_list)

for element in new_input_list:
   print(element)

#close input file
input_file.close()

I would appreciate any pointers.Thanks

Upvotes: 0

Views: 1808

Answers (2)

Zulu
Zulu

Reputation: 9285

You should look at http://docs.python.org/2/library/string.html#format-examples
There are a lot way to make simply table or other stuff quickly.

Official example:

width = 5
for num in range(5,12):
        for base in 'dXob':
            print '{0:{width}{base}}'.format(num, base=base, width=width),
        print

    5     5     5   101
    6     6     6   110
    7     7     7   111
    8     8    10  1000
    9     9    11  1001
   10     A    12  1010
   11     B    13  1011

Upvotes: 3

inspectorG4dget
inspectorG4dget

Reputation: 114035

Use the str.join syntax to print each row by itself

delim = '\t'  # tweak to your preference
for element in new_input_list:
    print(delim.join(str(i) for i in new_input_list))

Upvotes: 2

Related Questions