0

I have the snippet that sorts the contents of the text file. My problem is with the values after the scores as I am getting errors.

data = []
with open('data.txt') as f:
    for line in f:
        group, score, team = line.split(' ')
        data.append((int(score), group.strip(), team.strip()))

data.sort(reverse=True)
print("Top Scores:")
for (score, group, team), _ in zip(data, range(3)):
    print(f'{group} - {score} - {team}')    

datafile.txt (3 columns GROUP, SCORE, TEAM NAME)

asdsd 1 dream team
swsds 3 never mind us
2sdsg 1 diehard
sklks 2 just cool
asedd 5 dont do it

Error: #-- If there are no spaces in the last column, it works just fine.

ValueError: too many values to unpack (expected 3). 
rbutrnz
  • 383
  • 4
  • 20

2 Answers2

2

Split the line by ReGex:

import re
...

for line in j:
    group, score, team = re.split(r' (-?\d*\.?\d+) ', line.strip('\n').strip())
    
    data.append((int(score), group.strip(), team.strip()))
print(data)

Gives:

[(1, 'asdsd', 'dream team'), (3, 'swsds', 'never mind us'), (1, '2sdsg', 'diehard'), (2, 'sklks', 'just cool')]
1

Try with maxsplit parameter, which lets you define maximum how many splits you want:

data = []
for line in f:
    group, score, team = line.split(' ', maxsplit=2) #<-- maxsplit=2
    data.append((int(score), group.strip(), team.strip()))

OUTPUT:

Top Scores:
asedd - 5 - dont do it
swsds - 3 - never mind us
sklks - 2 - just cool
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45