-3

Complete beginner here, I am currently doing an exercise where I have to make Python read a text file with countries and scores and then I need to print the highest score first until the lowest score. So for example a text file could look like the following: Canada 14 Brazil 9 South Korea 16 (There are many other additional text files with different scores, but I start with the first one) My code until now:

firstscoredocument = f.readlines()
for line in firstscoredocument:
    nums_str = line.split()[1:]
    nums = [int(n) for n in nums_str]
    max_in_line = max(nums)
    print max_in_line

This code prints 14 9 16 I would need it to print South Korea 16 Canada 14 Brazil 9 Also, I can't seem to find a way how to print them from highest to lowest... Can anyone give me a hint please? thank you very much :)

Ankit Agrawal
  • 596
  • 5
  • 12
Okzupi
  • 1
  • You should be using Python 3 (where you'd write `print(max_in_line)`), Python 2 will be [end-of-life'd](https://en.wikipedia.org/wiki/Software_release_life_cycle#End-of-life) next month. – Boris Verkhovskiy Dec 01 '19 at 20:14

4 Answers4

1

Sorry to Say this !!! but don't use the Stack overflow to complete your homework problems. This will impact your reputation in the forum.

Here Pandas will help you in this, assume that you're using a tab delimited file.

from __future__ import print_function
import pandas as pd
data = pd.read_csv("sample_file.txt",sep='\t',header=None)
sort_by_life = data.sort_values(by=data.columns[1],ascending=False)
sort_by_life.to_csv("sort_by_life.txt", sep='\t', index=False, header=None)
print(sort_by_life)

Output:

South Korea 16
Canada  14
Brazil  9

Try to use Python 3, since python 2.x will be end of life.

Hope this helps you.

0

Read the file into a dictionary then sort the dictionary by values and print it out:

with open("filename.txt") as f:
    countries_to_scores = {}
    for line in f:
        country, score = line.strip().split()
        countries_to_scores[country] = score

for country in sorted(countries_to_scores, key=countries_to_scores.get):
    print(country, counties_to_scores[country])
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
-2
import os

with open(r'yourtextfile.txt', 'r') as f:
    firstscoredocument = [x.replace('\n', '') for x in f.readlines() if x != '\n']
    country_and_scores = []
    for line in firstscoredocument:
        if line == os.linesep:
            continue
        c, s = line.rsplit(' ', 1)
        country_and_scores.append([c, int(s)])

    country_and_scores.sort(key=lambda x: x[1], reverse=True) 
    for country_score in country_and_scores:
        print(*country_score )
nonamer92
  • 1,887
  • 1
  • 13
  • 24
  • there's no point to use `readlines` and checking for `os.linesep`, you can just do `for line in f` and then `if not line.strip(): continue`. Python automatically converts newlines to `\n` on all operating systems. – Boris Verkhovskiy Dec 02 '19 at 05:39
-2

I would suggest you read the values into a dictionary, then sort that by values. If you manage to create dictionary x in the example below, you will then be able to sort it and print it.

import operator
x = {"South Korea": 16, "Brazil": 9, "Canada": 14}
sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
print(sorted_x)
[('South Korea', 16), ('Canada', 14), ('Brazil', 9)]
pwwolff
  • 606
  • 1
  • 5
  • 20