-1

My task is to sort the scores(last 3 numbers) from highest to lowest. This works however, I would like each persons scores to be outputted on to seperate lines. How do i do this. This is my code:

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

list_data2 is a nested list:

[['Sid', 9, 8, 7], ['Tony', 9, 6, 4], ['Charlie', 4, 2, 1]]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • 2
    It would be a good idea to update the question with the input file structure and expected output as well. – fixxxer Apr 24 '15 at 20:43
  • Hi, I see you're new to SO. If you feel an answer solved the problem, please [mark it as 'accepted’](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) by clicking the green check mark. This helps keep the focus on older SO which still don't have answers. – fferri May 01 '18 at 18:24

1 Answers1

0

You could use a for loop, to print each nested list one by one:

>>> for data2 in list_data2:
        print(data2)

['Sid', 9, 8, 7]
['Tony', 9, 6, 4]
['Charlie', 4, 2, 1]

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

>>> for data2 in list_data2:
        print(*data2)

Sid 9 8 7
Tony 9 6 4
Charlie 4 2 1

The default separator when using print with multiple arguments is ' ', but you can change that using the keyword argument sep:

>>> for data2 in list_data2:
        print(*data2, sep='\t')

Sid     9   8   7
Tony    9   6   4
Charlie 4   2   1

Note that the tab width is dependent on your terminal settings. You can achieve a similar effect using a format string with fixed width columns (filled by space characters):

>>> for data2 in list_data2:
        print('%-12s %3d %3d %3d' % tuple(data2))

Sid            9   8   7
Tony           9   6   4
Charlie        4   2   1

However, this printf-like % syntax is deprecated, and you should use the new .format() method of str:

>>> for 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 for more examples)

fferri
  • 18,285
  • 5
  • 46
  • 95