BeardedTorus
BeardedTorus

Reputation: 13

Searching the the lowest Value from a file

I've included a test sample of my golf.txt file and the code I've used to print the results.

golf.txt:

Andrew

53

Dougie

21

The code to open this file and print the results (to keep this short I only have two players and two scores

golfData = open('golf.txt','r')
whichLine=golfData.readlines()


for i in range(0,len(whichLine),2):
  print('Name:'+whichLine[i])
  print('Score:'+whichLine[i+1])
golfData.close()

Can I modify the code I have to pull out the minimum player score with name? I believe I can without writing to a list or dictionary but have NO clue how.

Help/suggestions much appreciated.

Upvotes: 1

Views: 63

Answers (2)

IoaTzimas
IoaTzimas

Reputation: 10624

As @h0r53 indicated, you can try something like this:

golfData = open('golf.txt','r')
whichLine=golfData.readlines()

lowest=float('Inf')
Name=''

for i in range(0,len(whichLine),2):
  if float(whichLine[i+1])<lowest:
    lowest=float(whichLine[i+1])
    Name=whichLine[i]
golfData.close()

print(Name)
print(lowest)

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195543

Use min() function for that:

with open('file.txt') as f_in:
    min_player, min_score = min(zip(f_in, f_in), key=lambda k: int(k[1]))

print(min_player, min_score)

Prints:

Dougie
21

Upvotes: 1

Related Questions