0

I'm making a highscore list, and the order of it should determined by number of points, the second element of the lists in list. This is my code:

from typing import List, Tuple

name1 = 'John'
name2 = 'Ron'
name3 = 'Jessie'
points1 = 2
points2 = 3
points3 = 1

highscore: List[Tuple[str, int]] = []
highscore.append((name1, points1))
highscore.append((name2, points2))
highscore.append((name3, points3))

print(highscore)

sorted_by_second = sorted(highscore, key=lambda X: X[1])

highscore_list= str(sorted_by_second)

export list to file

with open('highscore.txt', 'w') as f:
for item in highscore_list:
    f.write("%s\n" % item)

Then it looks like this in the file:

 [
 (
 J
 e
 s
 s
 i
 e
 ,

 1
 )
 ,

But I want it to look like this in the file:

  Jessie 1
  John   2

How do I achieve this?

petezurich
  • 9,280
  • 9
  • 43
  • 57
what_in
  • 27
  • 6
  • You're iterating over a string, hence over each character in that string. Just omit the string conversion and format the output in your loop properly – Thomas Lang Dec 08 '18 at 16:28
  • look up f-strings. You are using typing on one hand and python 2.7 style string formatting on the other had - that does not fit well together : https://docs.python.org/3/reference/lexical_analysis.html#f-strings and https://docs.python.org/3/library/string.html#formatspec – Patrick Artner Dec 08 '18 at 16:34
  • I added a simple answer using dicts to the dupe I looked up. You find my answere [here](https://stackoverflow.com/a/53684733/7505395) and others using pickle as well – Patrick Artner Dec 08 '18 at 16:51
  • @Patrick Artner Thank you, learned something new! And I figured it out! – what_in Dec 08 '18 at 16:54

1 Answers1

1

Kudos on the (optional) typing declaration!

You started formatting it as a string a bit too early. Better to preserve the structure of your pairs a little longer:

for pair in sorted_by_second:
    f.write(f'{pair}\n')

Or if you prefer, break them out for more flexible formatting:

for name, points in sorted_by_second:
    f.write(f'{name} scored {points}.\n')
J_H
  • 17,926
  • 4
  • 24
  • 44
  • Thank you, it works perfectly! – what_in Dec 08 '18 at 16:53
  • I have a follow up question here: https://stackoverflow.com/questions/53691108/my-program-only-appends-one-user-input-to-list-when-main-is-looped-python-3 . Really appreciate if you could help me. – what_in Dec 09 '18 at 12:49