python - How to print on separate lines from a text file -


my task sort scores(last 3 numbers) highest lowest. works however, each persons scores outputted on seperate lines. how do this. code:

elif ask==2:     list_data2=[]     open('write_it.txt') f:           line in f:               line=line.split(',')               list_data2.append(sorted(line[:1])+sorted(map(int,line[2:]),reverse=true))     print (list_data2) 

list_data2 nested list:

[['sid', 9, 8, 7], ['tony', 9, 6, 4], ['charlie', 4, 2, 1]] 

you use loop, print each nested list 1 one:

>>> data2 in list_data2:         print(data2)  ['sid', 9, 8, 7] ['tony', 9, 6, 4] ['charlie', 4, 2, 1] 

but if want format in nicer way, pass multiple arguments print, print(data2[0], data2[1], data2[2], data2[3]), or in short, using print(*data2):

>>> data2 in list_data2:         print(*data2)  sid 9 8 7 tony 9 6 4 charlie 4 2 1 

the default separator when using print multiple arguments ' ', can change using keyword argument sep:

>>> data2 in list_data2:         print(*data2, sep='\t')  sid     9   8   7 tony    9   6   4 charlie 4   2   1 

note tab width dependent on terminal settings. can achieve similar effect using format string fixed width columns (filled space characters):

>>> data2 in list_data2:         print('%-12s %3d %3d %3d' % tuple(data2))  sid            9   8   7 tony           9   6   4 charlie        4   2   1 

however, printf-like % syntax deprecated, , should use new .format() method of str:

>>> data2 in list_data2:         print('{0:<12} {1:3d} {2:3d} {3:3d}'.format(*data2))  sid            9   8   7 tony           9   6   4 charlie        4   2   1 

(see https://docs.python.org/2/library/string.html#format-examples more examples)


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -