如何以漂亮的格式打印列表元组?

时间:2014-02-27 22:47:45

标签: python

我正在尝试以一种漂亮的格式打印出一个元组列表,这些格式将包含学生姓名,考试成绩1,考试成绩2和考试成绩平均值。我已经计算了平均值,所有内容都存储在元组列表中。但是,我的问题是格式化信息并打印出来。这是我的代码:

#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()

我很感激任何指针。谢谢

2 个答案:

答案 0 :(得分:3)

你应该看看http://docs.python.org/2/library/string.html#format-examples
有很多方法可以快速制作桌子或其他东西。

官方示例:

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

答案 1 :(得分:1)

使用str.join语法自行打印每一行

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